所以我想在一个有静态方法的方法上使用Mockito。原因是我无法使用PowerMock,因此我使用非静态方法封装了该方法。如何正确使用Mockito静态方法包装在非静态方法中?
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'。 – GhostCat
除了那个不清楚的地方:很好的第一个问题。我特别喜欢你的态度,以达到高品质(尽管我的答案在这里有不同的方向)**和**你的理解,你想避免PowerMock。我希望我能再次为你赢得三次胜利! – GhostCat
最后,再次无关:假设您正在使用Apache IOUtils.toString() - 请注意,此方法*弃用*,您应该使用取代编码的方法! – GhostCat