【发布时间】:2014-03-21 15:41:58
【问题描述】:
我有以下代码:
private MyService myService;
@Before
public void setDependencies() {
myService = Mockito.mock(MyService.class, new StandardServiceAnswer());
Mockito.when(myService.mobileMethod(Mockito.any(MobileCommand.class), Mockito.any(Context.class)))
.thenAnswer(new MobileServiceAnswer());
}
我的意图是所有对模拟 myService 的调用都应该以标准方式回答。但是,应以特定方式接听对mobileMethod(公开)的呼叫。
我发现,当我在线添加对mobileMethod 的调用的答案时,Java 实际上是在调用myService.mobileMethod,而不是附加myService.mobileMethod,这会导致NPE。
这可能吗?似乎应该可以覆盖默认答案。 如果可能,正确的做法是什么?
更新
这是我的Answers:
private class StandardServiceAnswer implements Answer<Result> {
public Result answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Command command = (Command) args[0];
command.setState(State.TRY);
Result result = new Result();
result.setState(State.TRY);
return result;
}
}
private class MobileServiceAnswer implements Answer<MobileResult> {
public MobileResult answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
MobileCommand command = (MobileCommand) args[0];
command.setState(State.TRY);
MobileResult result = new MobileResult();
result.setState(State.TRY);
return result;
}
}
【问题讨论】:
-
如果你的
@Before方法中有这个,那么你应该不能在测试中使用myService。你不是在隐藏一个实例变量吗?还是只是为了演示?另外,StandardServiceAnswer 是什么样子的? -
我已经更新了我的示例以清除它。
myService是测试类中的私有字段 -
抱歉给您带来了困惑……这是为了演示目的。
-
添加一个演示问题的简短测试方法。