Mockito验证方法调用的顺序/序列

是否有一种方法来验证在Mockito中methodOne是否在methodTwo之前被调用?

public class ServiceClassA {
public void methodOne(){}
}


public class ServiceClassB {
public void methodTwo(){}
}

public class TestClass {
public void method(){
ServiceClassA serviceA = new ServiceClassA();
ServiceClassB serviceB = new ServiceClassB();
serviceA.methodOne();
serviceB.methodTwo();
}
}
141619 次浏览

InOrder帮助你做到这一点。

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);


Mockito.doNothing().when(firstMock).methodOne();
Mockito.doNothing().when(secondMock).methodTwo();


//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);


//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

是的,这在文档中有描述。你必须使用有条不紊地进行类。

示例(假设已经创建了两个模拟):

InOrder inOrder = inOrder(serviceAMock, serviceBMock);


inOrder.verify(serviceAMock).methodOne();
inOrder.verify(serviceBMock).methodTwo();

注意,还可以使用有条不紊地进行类来验证在单个模拟上按顺序调用各种方法,而不仅仅是在两个或多个模拟上。

假设我有两个类FooBar:

public class Foo {
public void first() {}
public void second() {}
}


public class Bar {
public void firstThenSecond(Foo foo) {
foo.first();
foo.second();
}
}

然后我可以添加一个测试类来测试BarfirstThenSecond()方法实际上调用了first(),然后调用了second(),而不是second(),然后调用了first()。请看下面的测试代码:

public class BarTest {
@Test
public void testFirstThenSecond() {
Bar bar = new Bar();
Foo mockFoo = Mockito.mock(Foo.class);
bar.firstThenSecond(mockFoo);


InOrder orderVerifier = Mockito.inOrder(mockFoo);
// These lines will PASS
orderVerifier.verify(mockFoo).first();
orderVerifier.verify(mockFoo).second();


// These lines will FAIL
// orderVerifier.verify(mockFoo).second();
// orderVerifier.verify(mockFoo).first();
}
}

BDD是

@Test
public void testOrderWithBDD() {




// Given
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);


//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);


willDoNothing().given(firstMock).methodOne();
willDoNothing().given(secondMock).methodTwo();


// When
firstMock.methodOne();
secondMock.methodTwo();


// Then
then(firstMock).should(inOrder).methodOne();
then(secondMock).should(inOrder).methodTwo();




}

对于Kotlin用户,您可以这样做:

class MyTrackerTest {
private val trackEventUseCase: TrackEventUseCase = mock()
private val sut = MyTracker(trackEventUseCase)


@Test
fun `trackSomething SHOULD invoke tracker use case twice with correct event names WHEN called`() {
sut.trackSomething()


trackEventUseCase.inOrder {
verify().invoke("Is it August?")
verify().invoke("No!")
}
}