Let's assume a snippet of testing code:
Observable model = Class.forName(fullyQualifiedMethodName).newInstance(); Observer view = Mockito.mock(Observer.class); model.addObserver(view); for (Method method : Class.forName(fullyQualifiedMethodName).getDeclaredMethods()) { method.invoke(model, composeParams(method)); model.notifyObservers(); Mockito.verify( view, Mockito.atLeastOnce() ).update(Mockito.<Observable>any(), Mockito.<Object>any()); }
Mockito.verify
method throws an exception if a method in a model hasn't invoked Observable.setChanged()
method.
Problem: without adding loggers/System.print.out
I can't realize what's the current method that has failed the test. Is there a way of having something similar to jUnit Assert
methods:
Assert.assertEquals( String.format("instances %s, %s should be equal", inst1, inst2), inst1.getParam(), inst2.getParam() );
SOLUTION:
verify(observer, new VerificationMode() { @Override public void verify(VerificationData data) { assertTrue( format( "method %s doesn't call Observable#setChanged() after changing the state of the model", method.toString() ), data.getAllInvocations().size() > 0); } }).update(Mockito.<Observable>any(), Mockito.<Object>any());
Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.
Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.
The Assert command is used to validate critical functionality. If this validation fails, then the execution of that test method is stopped and marked as failed. In the case of Verify command, the test method continues the execution even after the failure of an assertion statement.
This question is ancient, but Mockito v2.1.0+ now has a built-in feature for this.
verify(mock, description("This will print on failure")).someMethod("some arg");
More examples included from @Lambart's comment below:
verify(mock, times(10).description("This will print if the method isn't called 10 times")).someMethod("some arg"); verify(mock, never().description("This will print if someMethod is ever called")).someMethod("some arg"); verify(mock, atLeastOnce().description("This will print if someMethod is never called with any argument")).someMethod(anyString());
This does the trick (simple and clear):
try { verify(myMockedObject, times(1)).doSomthing(); } catch (MockitoAssertionError error) { throw new MockitoAssertionError("Was expecting a call to myMockedObject.doSomthing but got ", error); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With