简体   繁体   中英

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?

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;
         }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM