[英]Unit test difference in mock and real object
以下是我的单元测试方法(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();
}
我正在使用Mock对象来模拟GetProducts
方法(依赖关系),并且在模拟中我返回已经声明的产品列表(_productList)。
我的问题是,当我调试测试时,我在模拟对象中通过的实际对象中没有得到相同的产品列表。根据我的探索,我们将在模拟对象中传递的实际结果中得到相同的对象列表。
有人可以建议我这是怎么回事吗?
我只想知道模拟对象返回与实际对象相同值的必要条件,或者可以更改它?
初始化_productService
,注入您要设置的_productDalMock
。 初始化_productDalMock
实例后,通常在_productService
的构造函数中完成此操作。
_productService = new ProductService(_productDalMock);
在调试中,验证_productService.GetProducts
代码最终到达_productDal.GetProducts
代码行。 也就是说,在DAL调用之前没有代码会使_productService.GetProducts
方法返回等。
如果您确保完成上述两个步骤,则退回的实际产品应与您通过的产品相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.