Fake/mock .Net Core Dependency injection Console App

Viewed 1876

I am trying to create Integration test, but it also depends on a third party service I want to fake. I have Console app .Net Core 3.1.

What I mean:

           var configuration = GetConfiguration();

            var serviceProvider = GetServiceProvider(configuration);

            var appService = serviceProvider.GetService<IConsumerManager>();

            appService.StartConsuming(commandLineArguments);
 private static IConfiguration GetConfiguration()
            => new ConfigurationBuilder().AddJsonFile(ConfigurationFile, true, true).Build(); 

private static ServiceProvider GetServiceProvider(IConfiguration config)
    {
        IServiceCollection collection = new ServiceCollection();

        collection.Configure<ConsumerConfig>(options => config.GetSection("consumerConfig").Bind(options));

        collection.AddSingleton<IConsumerManager, ConsumerManager>();
        collection.AddTransient<ISelfFlushingQueue, SelfFlushingQueue>();
        collection.AddTransient<IConsumer, Consumer>();
        collection.AddTransient<IConverter, Converter>();

        collection.AddFactory<IConsumerWorker, ConsumerWorker>();

        return collection.BuildServiceProvider();
    }

In my case I want to fake calls to Consumer. And I am wondering if there is other way to fake calls to it than just creating Fake class and adding it to DI. For example:

collection.AddTransient<IConsumer, FakeConsumer>(); 

Maybe somehow I could use FakeItEasy, NUnit or any other lib to fake this ?

1 Answers

You can create mocks using your favorite mocking framework and add them to your service collection.

Example using Moq:

var mock = new Mock<IConsumer>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true); // this line is just an example of mocking a method named DoSomething, you'll have to adapt it to the methods you want to mock

collection.AddTransient<IConsumer>(() => mock.Object); 

https://github.com/Moq/moq4/wiki/Quickstart

Related