简体   繁体   English

在 Mockito Junit 测试中发生检查异常时要断言或期望什么

[英]What to Assert or expect when checked exception occurs in Mockito Junit test

How to run a JUnit Test case on Checked Exception.如何在检查异常上运行 JUnit 测试用例。 For eg HttpClient execute method shows checked IOException but i am not sure what to assert/expect.例如,HttpClient 执行方法显示已检查的 IOException,但我不确定要断言/期望什么。

HttpClient httpClient = mock(HttpClient.class)



 try {
            when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
//Ideally nothing should work after this as exception is thrown
        //fail("This will fail") // this statement will throw Assertion Error
    }
    catch (IOException io) {
    
    }

If i try using expected method, this returns IOException never thrown.如果我尝试使用预期的方法,这将返回从未抛出的 IOException。

 Exception thrown =
                  assertThrows(
                          IOException.class,
                          () -> {
                           when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
                          });
    
          Truth.assertThat(thrown).hasMessageThat().contains("IOException");
        }

If I correctly understood, You need annotation @Test.如果我理解正确,您需要注释@Test。 And you should assign field "expected" your exception class.并且您应该将字段“预期”分配给您的异常类。

@Test(excepted = IOException.class)
testMethod() {
     throw new IOException();
}

In your test method you only stubbed httpClient.execute method, but never called it.在您的测试方法中,您只存根了httpClient.execute方法,但从未调用过它。 That is why no exception has been thrown.这就是为什么没有抛出异常的原因。

On top of that:最重要的是:

  • it is unclear what is object under test.目前尚不清楚什么是测试对象。 Mock collaborators, not object under test.模拟合作者,而不是被测对象。
  • if you only assert on message containing "IOException" string, you may prefer to assert that it is the instance of that class.如果您只对包含“IOException”字符串的消息进行断言,您可能更愿意断言它是该类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM