Nul*_*lpo 4 java hamcrest mockito
我想做这个:
when(myObject.getEntity(1l,usr.getUserName()).thenReturn(null);
when(myObject.getEntity(1l,Constants.ADMIN)).thenReturn(null);
Run Code Online (Sandbox Code Playgroud)
与匹配器合二为一。所以,我有这个代码:
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);
Run Code Online (Sandbox Code Playgroud)
但是当我使用 Or 匹配器时,JUnit 失败了:
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 ...
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
谢谢!
因为usr是模拟,所以内联方法调用usr.getUserName()是让你失望的部分。由于特定于 Mockito 的实现和语法巧妙的原因,您不能在存根另一个方法的中间调用模拟方法。
when(myObject.getEntity(
eq(1l),
or(eq(usr.getUserName()),eq(Constants.ADMIN))
)
).thenReturn(null);
Run Code Online (Sandbox Code Playgroud)
对 Mockito 匹配器的调用喜欢eq并or实际返回 0 和 null 等虚拟值,并且——作为副作用——它们将它们的 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);
Run Code Online (Sandbox Code Playgroud)
要了解有关 Mockito 匹配器如何在幕后工作的更多信息,请在此处查看我的其他 SO 答案。
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |