2

I have a piece of logic which is inserting a Product Model into a repository. The piece of logic will be inserting two product models both with different data into the repository and I need to test that this method is only called twice, once for each product.

public interface IProductRepo
{
    void AddProduct(IProductModel productModel);
}

public class ProductFactory
{
    IProductRepo productRepository;

    public ProductFactory(IProductRepo productRepo)
    {
        this.productRepository = productRepo;
    }

    public void AddProduct(IProductModel productModel)
    {
        this.productRepository.AddProduct(productModel);
    }
}

[TestMethod]
public void test()
{
    IProductModel productOne = Mock.Create<IProductModel>();

    Mock.Arrange(() => productOne.Name).Returns("ProductOne");
    Mock.Arrange(() => productOne.Price).Returns(99);

    IProductModel productTwo = Mock.Create<IProductModel>();

    Mock.Arrange(() => productTwo.Name).Returns("ProductTwo");
    Mock.Arrange(() => productTwo.Price).Returns(10);

    IProductRepo productRepo = Mock.Create<IProductRepo>();

    ProductFactory factory = new ProductFactory(productRepo);

    factory.AddProduct(productOne);
    factory.AddProduct(productTwo);

    // Test to see that both of these products being added called the IProductRepo.AddProduct() method.
}
Eritey
  • 143
  • 1
  • 2
  • 11

1 Answers1

2

UPDATE

based on comments, then you can call the assert twice. Once for each model.

Mock.Assert(() => productRepo.AddProduct(productOne), Occurs.Once());
Mock.Assert(() => productRepo.AddProduct(productTwo), Occurs.Once());

The assert would compare the args provided for equality when making the assertion.


Original answer

Referencing Asserting Occurrence from documentation,

consider using...

Mock.Assert(() => productRepo.AddProduct(Arg.Any<IProductModel>()), Occurs.Exactly(2));

in the minimal example provided above,

to see that both of these products being added called the IProductRepo.AddProduct() method.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • We considered this approach but it wouldn't confirm that the data inside of the Product models hasn't been modified. I'd like to be able to check the properties of the product model to check their the same as values as what we expect. – Eritey Dec 20 '17 at 09:09
  • @Eritey then you can call the assert twice . one for each model. – Nkosi Dec 20 '17 at 11:59