Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit testing, mocking - simple case: Service - Repository
    text
    copied!<p>Consider a following chunk of service:</p> <pre><code>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 } } } </code></pre> <p>Let's consider a simple unit test:</p> <pre><code>[Test] public void GetProduct_return_the_same_product_as_getProduct_on_productRepository() { var product = EntityGenerator.Product(); _productRepositoryMock.Setup(pr =&gt; pr.GetProduct(product.Id)).Returns(product); Product returnedProduct = _productService.GetProduct(product.Id); Assert.AreEqual(product, returnedProduct); _productRepositoryMock.VerifyAll(); } </code></pre> <p>At first it seems that this test is ok. But let's change our service method a little bit:</p> <pre><code>public Product GetProduct(int id) { try { var product = _productRepository.GetProduct(id); product.Owner = "totallyDifferentOwner"; return product; } catch (Exception e) { // log, wrap then throw } } </code></pre> <p>How to rewrite a given test that it'd pass with the first service method and fail with a second one?</p> <p>How do you handle this kind of <strong>simple</strong> scenarios?</p> <p><strong>HINT 1:</strong> A given test is bad coz product and returnedProduct is actually the same reference. </p> <p><strong>HINT 2:</strong> Implementing equality members (object.equals) is not the solution.</p> <p><strong>HINT 3:</strong> As for now, I create a clone of the Product instance (expectedProduct) with AutoMapper - but I don't like this solution.</p> <p><strong>HINT 4:</strong> I'm not testing that the SUT does NOT do sth. I'm trying to test that SUT DOES return the same object as it is returned from repository.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload