【发布时间】:2017-06-21 03:57:24
【问题描述】:
所以我试图在其中包含静态方法的方法上使用 Mockito。原因是我不能使用 PowerMock,所以我将该方法包装在非静态方法下。
public class WrapperUtil {
public String getURLContent(String path) throws IOException{
URL url = new URL(path);
return IOUtils.toString(url);
}
}
现在我以两种不同的方式测试 WrapperUtil 类。一个测试有效,但没有为 WrapperUtil 类提供任何覆盖,另一个是抛出与静态方法相关的空指针异常。
这是一个有效的,但没有提供任何覆盖。
@RunWith(MockitoJUnitRunner.class)
public class WrapperUtilTest {
@InjectMocks
WrapperUtil ioutils;
@Before
public void setUp() throws Exception {
ioutils = new WrapperUtil();
}
@Test
public void testGetUrlContent() throws IOException {
WrapperUtil ioutilsSpy = Mockito.spy(ioutils);
Mockito.doReturn("test").when(ioutilsSpy).getURLContent(Mockito.anyString());
assertTrue(ioutils2.getURLContent("test").contains("test"));
}
}
这是一个不起作用的:
@RunWith(MockitoJUnitRunner.class)
public class WrapperUtilTest {
@InjectMocks
WrapperUtil ioutils;
@Before
public void setUp() throws Exception {
ioutils = new WrapperUtil();
}
@Test
public void testGetUrlContent() throws IOException {
WrapperUtil ioutilsSpy = Mockito.spy(ioutils);
Mockito.when(ioutilsSpy).getURLContent(Mockito.anyString()).thenReturn("test");
assertTrue(ioutils2.getURLContent("test").contains("test"));
}
}
如何在不使用 PowerMockito 的情况下完成这项工作并实现代码覆盖?非常感谢你的帮助。
【问题讨论】:
-
无关:您的代码示例中有拼写错误。您声明
ioutils- 但随后您使用ioutils2。 -
除了有点不清楚:第一个问题很好。我特别喜欢你对实现高质量的态度(尽管我的回答在这里走向不同的方向)和你对你想要避免 PowerMock 的理解。我希望我能再为你投票 3 次!
-
最后,再次无关:假设您使用的是 Apache IOUtils.toString() - 请注意此方法已弃用,您应该使用采用编码的方法!
标签: java mockito code-coverage static-methods