【问题标题】:Unit test difference in mock and real object模拟和真实对象的单元测试差异
【发布时间】:2014-04-02 14:44:13
【问题描述】:

下面是我的单元测试方法(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)。

我的问题是当我调试测试时,我在实际对象中得到的产品列表与我在模拟中传递的产品列表不同。根据我的探索,我们将在实际结果中得到与我们传递的相同的对象列表模拟对象。

谁能告诉我这里出了什么问题?

编辑


我只是想知道模拟对象是否需要返回与实际对象相同的值,或者可以更改?

【问题讨论】:

  • 模拟数据和真实数据有什么区别?
  • 你用的是什么模拟框架? _productDalMock 是如何注入到 _productService 中的?
  • _productList的定义和初始化代码是什么?

标签: c# unit-testing mocking


【解决方案1】:
  1. 当您初始化 _productService 时,注入您正在设置的 _productDalMock。这通常在 _productService 的构造函数中完成,在您初始化 _productDalMock 实例之后。

    _productService = new ProductService(_productDalMock);
    
  2. 在您的调试中,确认_productService.GetProducts 代码最终到达_productDal.GetProducts 代码行。即在 DAL 调用之前没有代码可以使 _productService.GetProducts 方法返回等。

如果您确保以上两个步骤,那么实际退回的产品应该与您传递的产品相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多