mardi 2 mars 2021

Setup mock not working fine (returns exectuted repository method null value)

I have some problem when I setup my mock for add entity. In case when I want get entity/entites my mock-setup is working fine, but when I want create(add). I setup method for create and it returned null in result.

P.S AddProductAsync in my suspicion, this method may not work, although I checked in the debug, there is a call to the method

 public class ProductServiceTests
{
    private Mock<IProductRepository> _productMockRepo = new Mock<IProductRepository>();
    private ProductService _sut;

    public ProductServiceTests()
    {
        _sut = new ProductService(_productMockRepo.Object);
    }

It's my test method

[Fact]
    public async Task AddProduct_ShouldReturnProduct_WhenInputDataIsCorrect()
    {
        
        //Arrange
        var productId = Guid.NewGuid().ToString();
        var actualProduct = new ProductModel
        {
            Name = "test",
            Price = 1,
            Category = Category.Foods,
            Quantity = 2
        };
        
        var addingProduct = new Product
        {
            Name = actualProduct.Name,
            Price = actualProduct.Price,
            Category = actualProduct.Category,
            Quantity = actualProduct.Quantity
        };
        
        _productMockRepo.Setup(x => x.AddProductAsync(addingProduct))
            .ReturnsAsync(addingProduct);
        
        //Act
        var result = await _sut.AddProductAsync(actualProduct);
        
        //Assert
        
        Assert.Equal(actualProduct.Name, result.Name);
        _productMockRepo.Verify(x => x.AddProductAsync(addingProduct), Times.Once);
        

    }
}

_sut is my service and _productMockRepo is my mock repository

For testing I use NuGet packadge "Moq"

Thanks)

Aucun commentaire:

Enregistrer un commentaire