Search code examples
c#unit-testing.net-coremoqnsubstitute

Equivalent syntax of Moq's Mock.Get in Nsubstitute


I'm writing a unit test for my background service. It seems to be working if I use Moq framework but we are using NSubstitute within the team and would like to stick with that.

I was referring the code mentioned @How can i write unit test for my background service?.

I managed to convert the code syntax from Moq to NSubstitute except one line i.e. Mock.Get(service).

Could anyone help me convert the below code to use NSubstitute instead of Moq or let me know the equivalent syntax of Mock.Get(service) in NSubstitute.

 IServiceCollection services = new ServiceCollection();
 services.AddSingleton(Mock.Of<someobject>()); // Nsubstittute equivalent is services.AddSingleton(Substitute.For<someobject>());

 var serviceProvider = services.BuildServiceProvider();
 var service = serviceProvider.GetRequiredService<someobject>();

 var hostedService = serviceProvider.GetService<IHostedService>();
 await hostedService.StartAsync(CancellationToken.None);
 await Task.Delay(2000);
 await hostedService.StopAsync(CancellationToken.None);

 var mock = Mock.Get(service);
 mock.Verify(_ => _.SendQuote(), Times.Once);

Solution

  • Generally since nsub works directly with the mocked interface, you want to hold on to it in a variable.

    //Arrange
    IServiceCollection services = new ServiceCollection();    
    var mock = Substitute.For<someobject>(); //<-- THE MOCK
    services.AddSingleton(mock);
    //...add your hosted service that depends on the mock as needed
    
    var serviceProvider = services.BuildServiceProvider();
    var hostedService = serviceProvider.GetService<IHostedService>();
    
    //Act
    await hostedService.StartAsync(CancellationToken.None);
    await Task.Delay(2000);
    await hostedService.StopAsync(CancellationToken.None);
    
    //Assert
    mock.Received().SendQuote(); //<-- assert the mock directly