【发布时间】:2014-06-25 19:57:28
【问题描述】:
首先,请知道我在问这个问题之前已经搜索过 SO,但我找不到令人满意的答案。
我正在使用 JUnit4 和 Powermock 1.5.5(使用 mockito 1.9.5)
我的问题如下:在我的单元测试中,我需要在一个我无法修改的类中模拟一个静态方法。我只想模拟一个方法,而不是整个班级,所以我去找了一个间谍。
这是我目前所拥有的:
[...]
import static org.mockito.Matchers.*;
import static org.powermock.api.mockito.PowerMockito.*;
@RunWith(JUnitParamsRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-test.xml"},
loader=MockWebApplicationContextLoader.class)
@MockWebApplication(name="my-app")
@PrepareForTest(value = {
Role.class
})
public class MyTest {
@Rule
public PowerMockRule powerMockRule = new PowerMockRule();
@Before
public void setUp() throws Exception {
initSpring();
mockRoleServices();
}
private void mockRoleServices() throws Exception {
spy(Role.class);
RoleAnswer roleAnswer = new RoleAnswer(RoleEnum.ADMIN);
when(Role.hasAdministratorRole(anyLong(), anyLong(), anyLong()))
.then(roleAnswer);
}
private class RoleAnswer implements Answer<Boolean> {
private RoleEnum roleEnum;
private RoleAnswer(RoleEnum roleEnum) {
this.roleEnum = roleEnum;
}
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return getRenderRequest().getUserRole() != null &&
getRenderRequest().getUserRole().equals(roleEnum);
}
}
}
问题是:Role.hasAdministratorRole() 方法被调用而不是被模拟
这是我迄今为止尝试过的:
- 使用
mockStatic(Role.class)代替spy()方法。正如预期的那样,所有方法都被模拟了,所以我最终在调用Role.hasAdministratorRole()之前得到了一个 NPE - 像
doAnswer(...).when(...)这样的事情。我收到 powermock 运行时错误,告诉我我的模拟不完整(这实际上证实了我的代码或 lib 本身有问题) - 尝试通过名称声明方法而不是直接调用它:
when(Role.class, "hasAdministratorRole", long.class, long.class, long.class)。相同的行为 - 还有一堆我不记得了。
您的帮助将不胜感激。 谢谢!
编辑:感谢 SrikanthLingala 的回答,我能够查明问题所在。
这不起作用:
when(Role.hasAdministratorRole(anyLong(), anyLong(), anyLong()))
.thenAnswer(roleAnswer);
但是这样做了:
doAnswer(roleAnswer).when(Role.class, "hasSiteAdministratorRole",
anyLong(), anyLong(), anyLong());
所以切换然后when() 和answer() 工作
【问题讨论】:
-
另外,我注意到我试图模拟的类在类路径中的一个 jar 中(即不直接在类路径中)。这可能是相关的吗?
-
可能是因为你没有使用 PowerMockRunner 运行测试?
-
其他模拟工作,因为我正在使用 PowerMockRule。但无论如何,我测试了它,我得到了完全相同的输出:(
标签: java unit-testing junit4 powermock