所以我想在一個有靜態方法的方法上使用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