我正在爲我的控制器和服務層(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);
但在這裏我不理解這(上述單元測試)總是工作正常。意思是我們只是測試(在斷言中),我們通過了或者我們正在返回(在嘲笑對象中)。而且我們知道真實/實際對象將始終返回我們傳遞的列表或對象。
那麼在這裏做單元測試或嘲諷有什麼意義?
其清除所有的事情。 – Pawan