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的私人方法抛出的异常??
首先,它是测试私有方法的反图案。它不是您的API的一部分。请参阅已经链接的问题:使用Mockito
测试私人方法回答您的问题:当通过反射调用方法和调用方法会引发异常时,反射API将异常包装成InvocationTargetException。因此,您可以捕获InvocationTargetException并检查原因。
@Test
public void testGetTokenForExceptions() throws Exception {
HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
try {
method.invoke(null, mockHttpClient);
fail("should have thrown an exception");
} catch (InvocationTargetException e) {
assertThat(e.getCause(), instanceOf(BadCredentialsException.class));
}
}
您无法使用JUNIT甚至Mockito Framework测试私人方法。您可以在此问题中找到更多详细信息:使用Mockito
测试私人方法如果您确实需要测试此私人方法,则应使用PowerMock Framework。