I like to do something like the following:
.when( myMock.doSomething( Matchers.eq( "1" ) ) ) .thenReturn( "1" ) .othwerwise() .thenThrow( new IllegalArgumentException() );
Of course otherwise()
method doesn't exist but just to show you what I want to accomplish.
Argument matchers are mainly used for performing flexible verification and stubbing in Mockito. It extends ArgumentMatchers class to access all the matcher functions. Mockito uses equal() as a legacy method for verification and matching of argument values.
If you are using argument matchers, all arguments have to be provided by matchers. E.g: (example shows verification but the same applies to stubbing): verify(mock). someMethod(anyInt(), anyString(), eq("third argument")); //above is correct - eq() is also an argument matcher verify(mock).
Mockito mock() method All five methods perform the same function of mocking the objects. Following are the mock() methods with different parameters: mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
capture() it stores a matcher that saves its argument instead for later inspection. Matchers return dummy values such as zero, empty collections, or null . Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer. class) or an empty List<String> for anyListOf(String.
(Slight disclaimer, I've never done this personally, just read about it in the javadoc)... If all of your methods on your mock interface would be ok with the same default behaviour, you could set the default answer on your mock in a manner like:
Foo myMock = Mockito.mock(Foo.class,new ThrowsExceptionClass(IllegalArgumentException.class)); Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");
JavaDoc Links for: Mockito#mock and ThrowsExceptionClass
Alternatively, as is discussed in the Stubbing tutorial, order of the stubbing matters and last matching wins, so you might be able to also do:
Foo myMock = Mockito.mock(Foo.class); Mockito.when(myMock.doSomething(Matchers.any(String.class))).thenThrow(IllegalArgumentException.class); Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");
you could create your own Answer implementation which would pay attention to the called parameters:
myMock.doSomething(Mockito.any(String.class)).thenAnswer( myAnswer );
The implementation of said answer could do something like this:
public String answer(InvocationOnMock invocation) { if ("1".equals(invocation.getArguments()[0])) { return "1"; } else { throw new IllegalArgumentException(); } }
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