Fake/mock .Net Core 依赖注入控制台应用程序

Fake/mock .Net Core Dependency injection Console App

我正在尝试创建集成测试,但它还依赖于我想要伪造的第三方服务。 我有控制台应用程序 .Net Core 3.1。

我的意思是:

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

在我的例子中,我想伪造对消费者的调用。 我想知道除了创建 Fake class 并将其添加到 DI 之外,是否还有其他方法来伪造对它的调用。 例如:

collection.AddTransient<IConsumer, FakeConsumer>(); 

也许我可以用 FakeItEasy、NUnit 或任何其他库来伪造它?

您可以使用您最喜欢的模拟框架创建模拟并将它们添加到您的服务集合中。

使用最小起订量的示例:

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