Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Action<T> to Return Value Based on Parameters

This is a bit difficult to describe, but I need to mock/stub a method to return an instance of T based on inputs.

The message signature looks like:

T DoSomething<T>(Action<T> action);

Here is the code within the SUT:

var myEvent = _service.DoSomething<IMyEvent>(y =>
{
    y.Property1 = localProperty1;
    y.Property2 = localProperty2;
});

Here is what the setup should look like in my unit test:

service.Setup(x => x.DoSomething<IMyEvent>
         (It.IsAny<Action<IMyEvent>>())).Returns((
         (Action<IMyEvent> x) =>
         {
             return new MyEventFake //derives from IMyEvent
             {
                 Property1 = x.Property1,
                 Property2 = x.Property2
             };
         }));

This doesn't compile because x is an Action.

Is what I'm trying to do possible?

like image 446
Phil Sandler Avatar asked Nov 01 '22 18:11

Phil Sandler


1 Answers

Given your code sample, it seems you could just create a new MyEventFake, pass it to the action, and then just return it afterwards:

service.Setup(x => x.DoSomething<IMyEvent>
         (It.IsAny<Action<IMyEvent>>())).Returns((
         (Action<IMyEvent> x) =>
         {
              IMyEvent myEvent = new MyEventFake();
              x(myEvent);
              return myEvent;
         }));
like image 142
Patrick Quirk Avatar answered Nov 15 '22 04:11

Patrick Quirk