【发布时间】:2017-05-12 23:58:22
【问题描述】:
我想使用 Powermock 来测试一个私有方法(一个),但是这个私有方法依赖于另一个私有方法(两个)。
所以我必须模拟另一个私有方法。但是当我调试它时,结果发现私有方法一并没有调用模拟私有方法(二),如果我运行而不是调试它会抛出异常:
预计 1 个匹配者,记录 2 个。
private int getCurrentLocaleID(WebIServerSession currentSession, String preferenceName) {
String prefLocaleID = getUserPreference(currentSession, preferenceName);
int lcid;
if (HTTPHelper.isDefaultLocale(prefLocaleID)) {
prefLocaleID = _appContext.getBrowserHeaderLocaleId();
}
try {
lcid = Integer.parseInt(prefLocaleID);
} catch (NumberFormatException nfe) {
lcid = DEFAULT_LCID; // default behavior from old session manager
}
return lcid;
}
@Test
public void getCurrentLocaleID() throws Exception {
PowerMockito.mockStatic(HTTPHelper.class);
WebAppSessionManagerImpl webAppSessionMangerImpl2 = PowerMockito.spy(new WebAppSessionManagerImpl(appConext));
given(HTTPHelper.isDefaultLocale("1")).willReturn(true);
given(HTTPHelper.isDefaultLocale("0")).willReturn(false);
given(appConext.getBrowserHeaderLocaleId()).willReturn("1");
PowerMockito.doReturn("1").when(webAppSessionMangerImpl2, "getUserPreference", anyObject(), anyString());
int result = Whitebox.invokeMethod(webAppSessionMangerImpl2, "getCurrentLocaleID", webIserverSession, "test");
assertEquals(result, 1);
}
【问题讨论】:
-
仔细检查:你的测试类必须用
@RunWith(PowerMockRunner.class) @PrepareForTest({ HTTPHelper.class, WebAppSessionManagerImpl.class })注解
标签: java unit-testing mockito powermockito