简体   繁体   中英

Unit test difference in mock and real object

Below is my unit test method(c#) :-

[TestMethod]
public void ShouldReturnDtosWhenProductsFound_GetProducts()
{
    // Arrrange 
    var count = 0;
    var name = "myproduct";
    var description = "desc";

    // setup mocked dal to return  list of products
    // when name and description passed to GetProducts method
    _productDalMock.Setup(d => d.GetProducts(name, description)).Returns(_productList);

    // Act
    List<ProductDto> actual = _productService.GetProducts(name, description);

    // Assert
    Assert.IsNotNull(actual);
    Assert.IsTrue(actual.Any());
    Assert.AreEqual(_productList.Count, actual.Count);

    foreach (var product in _productList)
    {
        Adapter.AssertAreEqual(product, actual[count]);
        count++;
    }
    // verify all setups of mocked dal were called by service
    _productDalMock.VerifyAll();
}

I am using Mock object to mocking the GetProducts method(dependency).And in mocking i am returning the already declared product list(_productList).

My problem is when i am debugging the test,i am not getting the same product list in actual object as i passed in mocking.And according to my exploration we will get the same list of objects in actual result which we pass in mock object.

Can any one suggest me what is going wrong here ?

Edit


I just want to know its necessary for mock object to return the same values with actual object or it can be change ?

  1. When you initialize _productService , inject the _productDalMock you're setting up. This is typically done in the constructor of _productService , after you have initialized the _productDalMock instance.

     _productService = new ProductService(_productDalMock); 
  2. In your debugging, verify that the _productService.GetProducts code finally hits the _productDal.GetProducts code line. ie there is no code before the DAL call which would make the _productService.GetProducts method return etc.

If you ensure the above 2 steps, then the actual products returned should be same as the one you're passing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM