猿问

如何使用 NSubstitute 框架验证是否收到特殊类型的 AddSingleton

我想使用模拟库和.mock 来模拟IServiceCollection检查是否AddSingleton使用特定接口和具体类型进行调用。NsubstitexUnit


这是我的单元测试:


[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 :预计收到正好 1 个呼叫匹配:Add(ServiceDescriptor) 实际上没有收到匹配的呼叫。收到 1 个不匹配的呼叫(不匹配的参数以“*”字符表示):Add(*ServiceDescriptor *)


噜噜哒
浏览 101回答 1
1回答

米脂

AddSingleton是 上的扩展方法IServiceCollection。这使得模拟或验证变得更加困难。考虑使用接口的实际实现,然后在执行被测方法后验证预期行为。例如public void checkIfServicesAddedTo_DI() {&nbsp; &nbsp; //Arrange&nbsp; &nbsp; var services = new ServiceCollection();// Substitute.For<IServiceCollection>();&nbsp; &nbsp; var configuration = Substitute.For<IConfiguration>();&nbsp; &nbsp; MatchServicesManager servicesManager = new MatchServicesManager();&nbsp; &nbsp; //Act&nbsp; &nbsp; servicesManager.AddServices(services, configuration);&nbsp; &nbsp; //Assert (using FluentAssertions)&nbsp; &nbsp; services.Count.Should().Be(1);&nbsp; &nbsp; services[0].ServiceType.Should().Be(typeof(IMatchManager));&nbsp; &nbsp; services[0].ImplementationType.Should().Be(typeof(MatchManager));}
随时随地看视频慕课网APP
我要回答