模拟 .Net Core 依赖注入控制台应用程序

4

我正在尝试创建集成测试,但它也依赖于我想要伪造的第三方服务。我有一个控制台应用程序 .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();
    }

在我的情况下,我想伪造对Consumer的调用。 我想知道是否有其他方法来伪造它的调用,而不仅仅是创建Fake类并将其添加到DI中。 例如:

collection.AddTransient<IConsumer, FakeConsumer>(); 

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

1
你可以使用这个库:https://github.com/moq/moq 只需像这样创建消费者的模拟:Mock.Of<IConsumer>() 并将其注册为IConsumer。快速入门:https://github.com/Moq/moq4/wiki/Quickstart - Nikolay
1个回答

5

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

使用 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


我正在尝试做这件事,但是我遇到了一个“CS1593:委托'Func<IServiceProvider,IConsumer>'不接受0个参数”的错误。这让你想起什么吗? - Sebastián Vansteenkiste
1
可能已经更新了,并且它将一个输入作为参数。使用下面的代码应该可以工作。services.AddTransient<IYourServiceName>((_) => new Mock<IYourServiceName>().Object) - rakeshyadvanshi
AddTransient 对我也不起作用。但是 collection.AddSingleton(mock); 可以。 - vilem cech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接