tags:

views:

137

answers:

2

I have a class like:

public class Store
{
  public Store()
  {
     Products = new List<Product>();
  }
  public IList<Product> Products {get; private set;}
  public void AddProduct(int id, string productCode)
  {
     Product p = new Product();
     p.Id = id;
     p.ProductCode = productCode;            
     //Validate before adding
     Products.Add(p);  //How can i verify that this was called
  }
}

Using Moq how can i verify that the Add method of the Products List was called? Can someone provide a simple example?

+4  A: 

Well you can't really mock anything at the moment as the Products list is set up in the default constructor?

The easiest thing to do would be to assert against your products collection manually (i.e. just verify there's a product in there with the specified ID and Code) then you don't have to worry about mocking at all.

If you really want to use Moq to test this you need to provide a means to inject your Mock and get around your constructor, as an example you can provide two constructors

public class Store {

    public Store() : this(new List<Product>()) {

    }

    public Store(IList<Product> productList) {
       Products = productList
    }
    //Implementation
}

You can then write a test against your add method as follows

[Test]
public AddProduct_WithIdAndProductCode_AddsProductToCollection() {
    int productId = 0;
    string productCode = "a";    

    var productListMock = new Mock<IList<Product>>();
    Store store = new Store(productListMock.Object);

    store.AddProduct(productId, productCode);

    productListMock.Verify(pl => 
        pl.Add(It.Is<Product>(p => 
             p.Id == productId && p.ProductCode == productCode)));
}
sighohwell
+1  A: 

Do you need to test that add was called or that the list now has the expected number of items?

Assert.True(store.Products.Count == 1);
Aaron Fischer