Unit testing, mocking - simple case: Service - Repository
- by rafek
Consider a following chunk of service:
public class ProductService : IProductService {
   private IProductRepository _productRepository;
   // Some initlization stuff
   public Product GetProduct(int id) {
      try {
         return _productRepository.GetProduct(id);
      } catch (Exception e) {
         // log, wrap then throw
      }
   }
}
Let's consider a simple unit test:
[Test]
public void GetProduct_return_the_same_product_as_getProduct_on_productRepository() {
   var product = EntityGenerator.Product();
   _productRepositoryMock.Setup(pr => pr.GetProduct(product.Id)).Returns(product);
   Product returnedProduct = _productService.GetProduct(product.Id);
   Assert.AreEqual(product, returnedProduct);
   _productRepositoryMock.VerifyAll();
}
At first it seems that this test is ok. But let's change our service method a little bit:
public Product GetProduct(int id) {
   try {
      var product = _productRepository.GetProduct(id);
      product.Owner = "totallyDifferentOwner";
      return product;
   } catch (Exception e) {
      // log, wrap then throw
   }
}
How to rewrite a given test that it'd pass with the first service method and fail with a second one?
How do you handle this kind of simple scenarios?
HINT: A given test is bad coz product and returnedProduct is actually the same reference.