[英]Why does only the class with the static method have the error: “Add a private constructor to hide the implicit public one.”?
[英]Stub only one private static method in a class
我有一個正在單元測試的課程。 看起來如下:
public class classToUT {
public static Event getEvent(String id) {
return getEvent(id, null);
}
private static Event getEvent(String id, String name) {
//do something
logEvent(id, name);
return event;
}
private static void logEvent(String id, string name) {
// do some logging
}
}
我想避免在logEvent
中調用外部util方法。 基本上,我只想存根logEvent
,而在我的單元測試中要調用所有其他方法。 我如何僅存根這一種方法?
public void UTClass {
@Test
public void testGetEvent() {
assertNotNull(event, classToUt.getEvent(1)); //should not call logEvent
//but call real method for getEvent(1) and getEvent(1, null)
}
}
嘗試以下方法...
@RunWith(PowerMockRunner.class)
@PrepareForTest(PowerTest.ClassToUT.class)
public class PowerTest {
public static class ClassToUT {
public static String getEvent(String id) {
return getEvent(id, null);
}
private static String getEvent(String id, String name) {
// do something
logEvent(id, name);
return "s";
}
private static void logEvent(String id, String name) {
throw new RuntimeException();
}
}
@Test
public void testGetEvent() throws Exception {
PowerMockito.spy(ClassToUT.class);
PowerMockito.doNothing().when(ClassToUT.class, "logEvent", any(), any());
Assert.assertEquals("s", ClassToUT.getEvent("xyz"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.