[英]Verify the sequence of execution of methods in Xunit
我必須編寫測試用例來驗證鏈式方法的執行順序。 假設我已經編寫了如下所示的代碼
_store
.SetInput(input1)
.Method1()
.Method2()
.Method3();
如何編寫測試用例來檢查首先執行的 SetInput,第二個執行的方法,等等? 如果有人更改了方法鏈的實際實現或順序,那么測試用例應該會失敗。 我知道我不能模擬擴展方法,那么編寫測試用例來檢查方法執行順序的最佳方法是什么。
假設您的_store
實現了以下接口:
public interface IStore
{
IStore SetInput(string input);
IStore Method1();
IStore Method2();
IStore Method3();
}
為了簡單起見,這里是使用IStore
實現的類:
public class SystemUnderTest
{
private readonly IStore _store;
public SystemUnderTest(IStore store)
{
_store = store;
}
public void MyAction()
{
_store
.SetInput("input1")
.Method1()
.Method2()
.Method3();
}
}
因此,為了確保操作按此特定順序執行,我們可以使用MockSequence
( ref )。 這是一個示例單元測試:
[Fact]
public void GivenAFlawlessStore_WhenICallMyAction_ThenItCallsTheMethodsOfTheStoreInAParticularOrder()
{
//Arrange
var storeMock = new Mock<IStore>();
var expectedSequence = new MockSequence();
storeMock.InSequence(expectedSequence).Setup(x => x.SetInput(It.IsAny<string>()))
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method1())
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method2())
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method3())
.Returns(storeMock.Object);
var SUT = new SystemUnderTest(storeMock.Object);
//Act
SUT.MyAction();
//Assert
storeMock.Verify(store => store.SetInput("input1"), Times.Once);
}
如果您在單元測試中或在MyAction
方法中更改順序,它將失敗並返回NullReferenceException
,因為它無法在 null 上調用下一個方法。
更改MyAction
的順序
public void MyAction()
{
_store
.SetInput("input1")
.Method2()
.Method1() //NullReferenceException
.Method3();
}
改變MockSequence
的順序
//Arrange
var storeMock = new Mock<IStore>();
var expectedSequence = new MockSequence();
storeMock.InSequence(expectedSequence).Setup(x => x.SetInput(It.IsAny<string>()))
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method1())
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method3())
.Returns(storeMock.Object);
storeMock.InSequence(expectedSequence).Setup(x => x.Method2())
.Returns(storeMock.Object);
換句話說,您的Setup
調用不會提前產生任何影響。 當您從MyAction
調用SetInput
,第一個設置將按順序執行。 如果你試圖調用Method2
之前, Method1
的Setup
呼叫,則它會失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.