c# - 假/模拟 .Net Core 依赖注入(inject)控制台应用程序

标签 c# .net-core integration-testing

我正在尝试创建集成测试,但它还依赖于我想要伪造的第三方服务。 我有控制台应用程序 .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 类并将其添加到 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

关于c# - 假/模拟 .Net Core 依赖注入(inject)控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60613439/

相关文章:

java - Maven 故障安全插件失败并显示 "Unable to locate surefire-booter"

c# - 设置 CSVHelper 的列顺序

c# - UtcNow 到人类/系统友好的字符串

.net-core - 单元测试 Cors 是否添加到 ServiceCollection

c# - EF Core/DbContext > 将自定义类型映射为主键

JavaScript CLI : how to invoke bin file so that I can run integration tests with Jest

java - 将查询参数传递给 TestRestTemplate

c# - 如何使用 Selenium 和 C# 捕获整个页面截图

c# - MVVM light Messenger 中的 Action 、局部变量和垃圾收集的奇怪行为

c# - .net core/standard string.ToLower() 没有文化参数