Mocking Action <T> Parameter Based Return Value

This is a bit hard to describe, but I need to make fun of / stub the method to return an instance of T based on the inputs.

The message signature looks like this:

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

Here is the code inside SUT:

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

This is what the setup looks 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 does not compile because x is an action.

Am I trying to do this?

+5
source share
1 answer

Given your code example, it seems you can just create a new MyEventFake , pass it into action, and then just return it after:

 service.Setup(x => x.DoSomething<IMyEvent> (It.IsAny<Action<IMyEvent>>())).Returns(( (Action<IMyEvent> x) => { IMyEvent myEvent = new MyEventFake(); x(myEvent); return myEvent; })); 
+2
source

Source: https://habr.com/ru/post/1200255/


All Articles