C# Fake/mock.Net核心依赖项注入控制台应用程序

C# Fake/mock.Net核心依赖项注入控制台应用程序,c#,.net-core,integration-testing,C#,.net Core,Integration Testing,我正在尝试创建集成测试,但它也取决于我想要伪造的第三方服务。 我有控制台应用程序.Net Core 3.1 我的意思是: var configuration = GetConfiguration(); var serviceProvider = GetServiceProvider(configuration); var appService = serviceProvider.GetService<IConsume

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

我的意思是:

           var configuration = GetConfiguration();

            var serviceProvider = GetServiceProvider(configuration);

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

            appService.StartConsuming(commandLineArguments);
var-configuration=GetConfiguration();
var serviceProvider=GetServiceProvider(配置);
var appService=serviceProvider.GetService();
appService.StartConsuming(命令行参数);
private静态IConfiguration GetConfiguration()
=>新建ConfigurationBuilder().AddJsonFile(ConfigurationFile,true,true).Build();
专用静态服务提供程序GetServiceProvider(IConfiguration配置)
{
IServiceCollection collection=newServiceCollection();
Configure(options=>config.GetSection(“consumerConfig”).Bind(options));
collection.AddSingleton();
collection.AddTransient();
collection.AddTransient();
collection.AddTransient();
collection.AddFactory();
返回集合。BuildServiceProvider();
}
在我的情况下,我想假装打电话给消费者。 我想知道除了创建假类并将其添加到DI之外,是否还有其他方法可以伪造对它的调用。 例如:

collection.AddTransient<IConsumer, FakeConsumer>(); 
collection.AddTransient();

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

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

使用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); 
var mock=new mock();
mock.Setup(foo=>foo.DoSomething(“ping”))。返回(true);//这一行只是模拟名为DoSomething的方法的一个示例,您必须使其适应您想要模拟的方法
collection.AddTransient(()=>mock.Object);

您可以使用此库:只需像这样创建消费者的mock:mock.of()并将其注册为IConsumer。快速启动:
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);