在JUnit中声明私有方法的异常

问题描述 投票:1回答:2
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私有方法引发的异常吗?

exception junit mockito
2个回答
1
投票

首先,它是一个测试私有方法的反模式。它不是您的API的一部分。查看已经链接的问题:Testing Private method using mockito

回答你的问题:当通过Reflection调用方法并且被调用的方法抛出异常时,Reflection API将Exception包装到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));
    }
}

0
投票

您无法使用JUnit或甚至使用Mockito框架测试私有方法。您可以在此问题中找到更多详细信息:Testing Private method using mockito

如果您确实需要测试此私有方法,则应使用PowerMock框架。

© www.soinside.com 2019 - 2024. All rights reserved.