Mockitovalidation方法调用的顺序/顺序

有没有办法来validationmethodTwo之前调用methodTwo在Mockito?

 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(); } } 

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类。

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

 InOrder inOrder = inOrder(serviceAMock, serviceBMock); inOrder.verify(serviceAMock).methodOne(); inOrder.verify(serviceBMock).methodTwo(); 

请注意,您也可以使用InOrder类来validation在单个模拟中调用各种方法的顺序,而不仅仅是两个或多个模拟。

假设我有两个类FooBar

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

然后我可以添加一个testing类来testingBarfirstThenSecond()方法实际上是first()调用first() ,然后是second() ,而不是second() ,然后是first() 。 请参阅以下testing代码:

 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(); } }