Unit testing, mocking - simple case: Service - Repository

Posted by rafek on Stack Overflow See other posts from Stack Overflow or by rafek
Published on 2010-05-08T06:29:23Z Indexed on 2010/05/08 6:38 UTC
Read the original article Hit count: 244

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about mocking