【发布时间】:2018-06-07 05:51:48
【问题描述】:
private static String getToken(HttpClient clientInstance) throws badcredentailsexception{
try{
// some process here throws IOException
}
catch(IOexception e){
throw new badcredentailsexception(message, e)
}
}
现在我需要为上述方法编写Junit测试,我的上述函数的Junit代码如下
@Test(expected = badcredentailsexception.class)
public void testGetTokenForExceptions() throws ClientProtocolException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenThrow(IOException.class);
// mocked mockHttpClient to throw IOException
final Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
Object actual = method.invoke(null, mockHttpClient);
}
但是这个测试没有通过,有什么改进吗??
我们可以检查 junit 的私有方法抛出的异常吗??
【问题讨论】:
-
1.解释你的测试没有通过是什么意思。你有什么例外吗? 2. 我不认为你可以使用 Mockito 测试私有方法。你应该使用 Powermockito
-
测试方法调用
getToken(HttpClient),但您的方法没有HttpClient参数。这是由于复制/粘贴还是您有两个getTokenmethods? -
函数需要一个参数,现在编辑@RolandWeisleder
-
@pvpkiran 我期待 badcredentailsexception,但我从 method.invoke 语句中得到调用目标异常以及 Junit 跟踪中的错误凭据异常