gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:56:18 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com