【问题标题】:How to test that the method doesn't throw an exception?如何测试该方法不会引发异常?
【发布时间】:2018-03-01 20:54:14
【问题描述】:

当您期望目标方法抛出异常时,这就是您编写测试的方式。

@Test(expected = myExpectedException.class)
public void Test()
{

}

如果方法没有抛出异常就成功了怎么办?有那个属性吗?

【问题讨论】:

    标签: java exception junit


    【解决方案1】:

    如果测试方法抛出异常,则认为该测试处于 ERROR 状态,不计入 PASSED 测试。 换句话说——你不需要任何特殊待遇。只需调用您要测试的方法即可。

    如果您想明确表示不允许异常,可以在测试中添加ExpectedException 规则:

    public class MyClassTest {
        // The class under test
        // Initialized here instead of in a @Before method for brevity
        private MyClass underTest = new MyClass();
    
        // Not really needed, just makes things more explicit
        @Rule
        public ExpectedException noExceptionAllowed = ExpectedException.none();
    
        @Test
        public void testSomeMethod() throws SomeException {
            // If an exception is thrown, the test errors out, and doesn't pass
            myClass.someMethod();
        }
    }
    

    【讨论】:

      【解决方案2】:

      不抛出异常并且同时不预期它总是成功 但是,如果您明确希望您的测试告诉 Spec 该方法可能会引发异常,但这次不是,您可以使用类似这样的方法

      (在我的档案中找到了这段代码。我记得我从互联网上引用过它)

      class MyAssertionRules {
          public static void assertDoesNotThrow(FailableAction action) {
              try {
                  action.run();
              } catch (Exception ex) {
                  throw new Error("Unexpected Exception Thrown", ex);
              }
          }
      }
      
      @FunctionalInterface
      interface FailableAction {
          void run() throws Exception;
      }
      

      然后你可以像这样运行你的测试

      public void testMethodUnderTest() {
          MyAssertionRules.assertDoesNotThrow(serviceUnderTest::methodUnderTest);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-05
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 2018-01-03
        • 1970-01-01
        • 2014-05-04
        • 2019-03-09
        相关资源
        最近更新 更多