I have a service that is implemented in a separate library and is taking a Func<T>
as a parameter of a function.
When mocking the service I still need my Func<T>
to be run.
How do I setup the mock object for this?
I have created the following code example to demonstrate the problem:
// This is the service that is in a different library and I want to mock
public interface IServiceToMock
{
T ExecuteAsync<T>(Func<T> func);
}
public class ServiceToMock : IServiceToMock
{
public T ExecuteAsync<T>(Func<T> funcToBeExecuted)
{
// does some more logic that I don't want to test
return funcToBeExecuted();
}
}
This is the consumer of the service
public class ServiceConsumer
{
private readonly IServiceToMock service;
public ServiceConsumer(IServiceToMock service) => this.service = service;
public async Task Consume()
{
await service.ExecuteAsync(async () => await ConsumeInteger(1));
await service.ExecuteAsync(async () => await ConsumeString("String"));
}
// This is the method that I want to be triggered when the Consume() is called
private async Task ConsumeInteger(int number)
{
await new Task<int>(() =>
{
Console.WriteLine(number);
return number;
});
}
// This is the method that I want to be triggered when the Consume() is called
private async Task ConsumeString(string str)
{
await new Task<string>(() =>
{
Console.WriteLine(str);
return str;
});
}
}
This is the test I have so far
public class TestServiceConsumer
{
public void TestMethod()
{
var moqLibraryService = new Mock<IServiceToMock>();
// How can I set up the mock to have the Console
moqLibraryService.Setup(ms => ms.ExecuteAsync(It.IsAny<Func<T>>())).Returns(T());
}
}