I have a Java class:
import java.util.List;
public class Service
{
public List<Object> someMethod(final List<Object> list) {
return null;
}
}
And a Spock test where I've defined a custom matcher:
import org.mockito.ArgumentMatcher import spock.lang.Specification
import static org.mockito.Mockito.*
class InstantBookingInitialDecisionTest extends Specification {
def mock = mock(Service.class)
def setup() {
when(mock.someMethod(argThat(hasSize(2)))).thenReturn([])
when(mock.someMethod(argThat(hasSize(3)))).thenReturn([])
}
def 'Minimum hunger requirements do not apply to schedulable pros'() {
when:
'something'
then:
'something else'
}
// Damn, there's a Hamcrest matcher for this, but it's not in the jar that the javadocs say it is, so making my own
static def hasSize(size) {
new ArgumentMatcher<List>() {
@Override
boolean matches(Object o) {
List list = (List) o
return list.size() == size
}
}
}
}
As is, this test gives me the following error:
java.lang.NullPointerException: Cannot invoke method size() on null object
If I remove either one of the when
's, I get no error. So what it doesn't like is the stubbing portion of the test, and the fact that I used the custom matcher twice.
Notes:
- I've tried declaring a separate class for each list size, as in mockito anyList of a given size and the Mockito documentation. I get the same error.
- I've tried to use the Hamcrest matcher that looks like this, but despite the fact that the 1.3 Javadocs lists a Matchers.hasSize() method, my imported 1.3 jar does not include Matchers. (But even if I got the dependency resolved, I would still like to understand the problem.)
Please do not ask why I am using Mockito instead of Spock Mocks - I have my reasons. ;)
Thank you