【问题标题】:Expect exception when using JUnit Theory使用 JUnit 理论时会出现异常
【发布时间】:2012-10-24 13:35:26
【问题描述】:

在 JUnit 4 中,您可以使用 @Test(expected = SomeException.class) 注释声明预期的异常。但是,当使用 Theories 进行测试时,@Theory 注释不具有 expected 属性。

在测试 Theories 时声明预期异常的最佳方式是什么?

【问题讨论】:

    标签: java testing exception-handling junit junit4


    【解决方案1】:

    我更喜欢使用ExpectedException rule

    import org.junit.rules.ExpectedException;
    
    <...>
    
    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Theory
    public void throwExceptionIfArgumentIsIllegal(Type type) throws Exception {
        assumeThat(type, equalTo(ILLEGAL));
        thrown.expect(IllegalArgumentException.class);
        //perform actions
    }
    

    【讨论】:

      【解决方案2】:

      您也可以使用普通的assert。您可以在旧版本的 JUnit(4.9 之前)上使用它。

      @Test
      public void exceptionShouldIncludeAClearMessage() throws InvalidYearException {
          try {
              taxCalculator.calculateIncomeTax(50000, 2100);
              fail("calculateIncomeTax() should have thrown an exception.");
          } catch (InvalidYearException expected) {
              assertEquals(expected.getMessage(),
                           "No tax calculations available yet for the year 2100");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 2015-02-13
        • 2013-08-17
        相关资源
        最近更新 更多