MSDoc: Unit testing best practices with .NET Core and .NET Standard
The main thing to remember about mocks versus stubs is that mocks are just like stubs, but you assert against the mock object, whereas you don't assert against a stub.
总结:只会断言 Mock
,不会断言 Stub
。
// Stub
[TestMethod]
public void ValidateOrders_StubTest()
{
var stubOrder = new FakeOrder();
var purchase = new Purchase(stubOrder);
purchase.ValidateOrders();
Assert.True(purchase.CanBeShipped);
}
// Mock
[TestMethod]
public void ValidateOrdersTest_MockTest()
{
var mockOrder = new FakeOrder();
var purchase = new Purchase(mockOrder);
purchase.ValidateOrders();
Assert.True(mockOrder.Validated);
}
Stub
和 Mock
都是 Fake
的一种:
通常 Stub
主要用来返回结果;
而 Mock
则可以设置某种行为,从而对这个行为进行校验。
在落地实施过程中,其实不太区分,直接把 Mock
当 Setup
用,比如 Moq
的设计,就是不区分的。
Comments