【问题标题】:Asserting Exceptions for private method in JUnit在 JUnit 中断言私有方法的异常
【发布时间】: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 跟踪中的错误凭据异常

标签: exception junit mockito


【解决方案1】:

首先,测试私有方法是一种反模式。它不是您的 API 的一部分。查看已经链接的问题:Testing Private method using 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));
    }
}

【讨论】:

    【解决方案2】:

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

    如果你真的需要测试这个私有方法,你应该使用 PowerMock 框架。

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2012-01-24
      • 2020-07-29
      • 2019-01-28
      相关资源
      最近更新 更多