I have a service named MyService which implements IService and my AppContext (inherits from DbContext) gets injected into this service. It has a method called AddProduct(ProductDTO) which returns just a Task, as it is just an Insert. I map the input parameter, ProductDTO to Product entity within this method and I call _appContext.AddAsync(mappedentity) and _appcontext.SaveChangesAsync() within this method.
Now, I have written a unit test case in NSubstitute to add the product by calling the above method in my service. Even though the main app that hits this service method is working just fine and is creating the product, this test case keeps failing with the error "Expected to receive exactly one call. But did not receive any calls".
This is the test case code. I am unsure why this is failing at the first assert on Received. I tried both Add() as well as AddAsync() and likewise with SaveChanges().
public class MyServiceTests
{
[Fact]
public async Task AddProduct_ShouldAddProductToContext()
{
// Arrange
var appContext = Substitute.For<IAppContext>();
var myService = new MyService(appContext);
var productDTO = new ProductDTO
{
// Initialize properties for the ProductDTO
// ...
};
// Act
await myService.AddProduct(productDTO);
// Assert
await appContext.Received(1).Add(Arg.Any<Product>());
await appContext.Received(1).SaveChanges();
}
}
The mistake I had made was in the asserts. The last two lines need to be replaced with this.
I was missing true on the SaveChanges and I was not checking the Received on the Products dbset.