Problems with "OR" Matcher in When a Predicate with Mockito

I want to do this:

when(myObject.getEntity(1l,usr.getUserName()).thenReturn(null);
when(myObject.getEntity(1l,Constants.ADMIN)).thenReturn(null);

on one line using sockets. So, I have this code:

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.mockito.AdditionalMatchers.*;

[...]

User usr = mock(usr);

[...]

when(myObject.getEntity(
    eq(1l), 
    or(eq(usr.getUserName()),eq(Constants.ADMIN))
    )
).thenReturn(null);

But when I use a match, JUnit fails:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded.
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.
    at blah.blah.MyTestClass.setup(MyTestClass:The line where I use the when & or matcher)
... more stacktrace ...

What am I doing wrong?

Thanks!

+4
source share
1 answer

Because it usris a layout, calling the inline method usr.getUserName()is the part that drops you. You cannot call the bullying method in the middle of the start of another method for reasons specific to the implementation of Mockito and the ability to syntax.

when(myObject.getEntity(
    eq(1l), 
    or(eq(usr.getUserName()),eq(Constants.ADMIN))
    )
).thenReturn(null);

Mockito, eq or, , 0 , - Matcher ArgumentMatcherStorage. Mockito , , , (.. ) (.. , ). .

Java, eq(1l) , usr.getUserName() - or. , getUserName , 0 1 .

:

String userName = usr.getUserName(); // or whatever you stubbed, directly
when(myObject.getEntity(
    eq(1l), 
    or(eq(userName),eq(Constants.ADMIN))
    )
).thenReturn(null);

, Mockito , . SO .

+4

All Articles