【发布时间】:2014-04-01 10:54:49
【问题描述】:
我正在为我的控制器和服务层(C#、MVC)进行单元测试。我正在使用 Moq dll 在单元测试中模拟真实/依赖对象。
但我对模拟依赖项或真实对象有点困惑。让我们以下面的单元测试方法为例:-
[TestMethod]
public void ShouldReturnDtosWhenCustomersFound_GetCustomers ()
{
// Arrrange
var name = "ricky";
var description = "this is the test";
// setup mocked dal to return list of customers
// when name and description passed to GetCustomers method
_customerDalMock.Setup(d => d.GetCustomers(name, description)).Returns(_customerList);
// Act
List<CustomerDto> actual = _CustomerService.GetCustomers(name, description);
// Assert
Assert.IsNotNull(actual);
Assert.IsTrue(actual.Any());
// verify all setups of mocked dal were called by service
_customerDalMock.VerifyAll();
}
在上面的单元测试方法中,我模拟了 GetCustomers 方法并返回一个客户列表。这已经定义了。如下所示:
List<Customer> _customerList = new List<Customer>
{
new Customer { CustomerID = 1, Name="Mariya",Description="description"},
new Customer { CustomerID = 2, Name="Soniya",Description="des"},
new Customer { CustomerID = 3, Name="Bill",Description="my desc"},
new Customer { CustomerID = 4, Name="jay",Description="test"},
};
让我们看看客户模拟对象的断言和实际对象断言:-
Assert.AreEqual(_customer.CustomerID, actual.CustomerID);
Assert.AreEqual(_customer.Name, actual.Name);
Assert.AreEqual(_customer.Description, actual.Description);
但在这里我不明白它(在单元测试之上)总是可以正常工作。意味着我们只是在测试(在断言中)我们通过了或者我们正在返回(在模拟对象中)。而且我们知道真实/实际对象将始终返回我们传递的列表或对象。
那么这里做单元测试或者模拟是什么意思呢?
【问题讨论】:
标签: c# unit-testing mocking