gpt4 book ai didi

c# - 如何使用 NSubstitute 框架验证接收到具有特殊类型的 AddSingleton

转载 作者:行者123 更新时间:2023-12-04 13:18:33 25 4
gpt4 key购买 nike

我想模拟 IServiceCollection 以使用 Nsubstite 模拟库和 检查是否使用特定接口(interface)和具体类型调用了 AddSingleton xUnit.

这是我的单元测试:

[Fact] 
public checkIfServicesAddedTo_DI()
{
var iServiceCollectionMock = Substitute.For<IServiceCollection>();
var iConfiguration = Substitute.For<IConfiguration>();
MatchServicesManager servicesManager = new MatchServicesManager();
servicesManager.AddServices(iServiceCollectionMock, iConfiguration);

iServiceCollectionMock.Received(1).AddSingleton(typeof(IMatchManager) , typeof(MatchManager));
}

这是实现:

public class MatchServicesManager : IServicesManager
{
public void AddServices(IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IMatchManager, MatchManager>();
}
}

我希望测试成功,但它失败并出现以下错误:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receiveexactly 1 call matching: Add(ServiceDescriptor) Actually received nomatching calls. Received 1 non - matching call(non - matchingarguments indicated with '*' characters): Add(*ServiceDescriptor *)

最佳答案

AddSingletonIServiceCollection 的扩展方法。这使得模拟或验证变得更加困难。

考虑使用接口(interface)的实际实现,然后在执行被测方法后验证预期行为。

例如

public void checkIfServicesAddedTo_DI() {
//Arrange
var services = new ServiceCollection();// Substitute.For<IServiceCollection>();
var configuration = Substitute.For<IConfiguration>();
MatchServicesManager servicesManager = new MatchServicesManager();

//Act
servicesManager.AddServices(services, configuration);

//Assert (using FluentAssertions)
services.Count.Should().Be(1);
services[0].ServiceType.Should().Be(typeof(IMatchManager));
services[0].ImplementationType.Should().Be(typeof(MatchManager));
}

关于c# - 如何使用 NSubstitute 框架验证接收到具有特殊类型的 AddSingleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57123686/

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