【发布时间】:2013-09-22 07:41:16
【问题描述】:
我有一个类是Context 的子类。我正在对另一个依赖于这个类的类进行单元测试,因此我嘲笑了它。但是,我需要一些方法来充当它们的原始行为,所以我要“取消模拟”它们。
其中一个是getAssets(),所以我写了这个并且它工作正常:
Mockito.doReturn(this.getContext().getAssets()).when(keyboard).getAssets();
keyboard 是上述类的模拟实例。
由于此方法不带参数,因此覆盖它非常简单。
我也需要覆盖Context.getString(int)。该参数使事情变得困难,它是一个原始的,使事情变得更加困难。
我拿了this advice 和另一个,并尝试编写这段代码:
Mockito.when(keyboard.getString(Mockito.anyInt())).thenAnswer(new Answer<String>(){
@Override
public String answer(InvocationOnMock invocation) throws Throwable
Integer arg = (Integer)invocation.getArguments()[0];
return OuterClass.this.getContext().getString(arg.intValue());
}
});
编译并执行,但出现以下异常:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at [...] <The code above>
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 android.content.Context.getString(Context.java:282)
at [...]
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:545)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)
所以主要问题是如何覆盖 Mockito 中具有原始参数的方法?
提前致谢
【问题讨论】:
-
我无法重现您的错误。如果你搜索
InvalidUseOfMatchersException,你会发现一堆相关的问题和答案。问题是您正在调用一个带有一个 Matcher 参数和一个没有的 Mockito 方法,由于各种原因,这是不允许的。 -
感谢您的尝试。是的,我已经在搜索并且仍在搜索。
标签: java android unit-testing mockito