c# - Why does my object mocking fail? -


I am using Moq and can not seem to get my unit exam that is a simple funny scenario .

Products P = new product (); Var rep = new mock & lt; IProductRepository & gt; (); Representative (x = & gt; x.GetProductById (1)). Return (p); P = Representative Object. GetProductById (1); Assurance First (1, P. Product ID); //Assert.AreEqual failed Expectancy: & lt; 1> Actual: & lt; 0>

Any sign on what I'm doing wrong? My unit exam report: -

Apprehension. Expectancy: & lt; 1>. Actual: & lt; 0>.

I think you are missing out on the fact that mock in tests Use the object ...

The productive repository that you are doing is joking, while testing it simultaneously. It does not matter much; You should not duplicate the object that you are testing

Assume that you have a class that you want to test, product service, and this depends on another class, IProductRepository is. When you check the product service, you want to copy the dependency , IProductRepository. This allows you to completely control the class between the test and its dependency (exhaustion).

After doing so, your claim will be given to you based on the expectation of the classroom under trial, product service. For example, if you say something like ProductService to productService.GetProductById (1) , you would expect that the ProductService object to call its IP product repository method once with the correct parameter : repository.GetProductById (1) . You can also expect that the product service has returned the same item which IP product registrar gave it to.

After saying this, your test may look like something else:

  // int testId = 1; Var fakeProduct = new product {id = test id}; Var Mock Repos = New Fake & lt; IRepository & gt; (); Var productService = New Product Service (Fake Rippo); Fake repos Expect (repo = & gt; repo getProductById (testId)). Returns (fake product); // Act Product Back Product = Product Service GETProductById (testId); // Announce vocal repos. Verify (repo = & gt; repo gateproduct BIID (test id), timeexactly (1)); Relax. Immovable (back product.ID, fake product ID);  

My syntax may be turned off, but hopefully the sample will be at some point:

  1. Fake system system under test
  2. Copy the dependency

Comments