[英]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.