【问题标题】:Exception assertion along with other assertions jUnit异常断言以及其他断言 jUnit
【发布时间】:2013-07-03 13:09:09
【问题描述】:

我有一个抛出异常的方法。我有一个这样的测试。

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
    doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());

    expectedEx.expect(InvalidException.class);
    expectedEx.expectMessage("Invalid Token");

    // my method call

    // verify DB save doesn't happens

    assertTrue(false);
}

测试断言异常,并且由于抛出异常,测试通过。它不关心最后一行assertTrue(false)

我如何确保我的其他断言也得到满足。

【问题讨论】:

    标签: exception junit junit4 junit-rule


    【解决方案1】:

    这是我在这个案例中遵循的模式。它按照设计使用ExpectedException。我喜欢throw e,而不是在try 中的方法调用后失败,因为如果有人决定删除fail(人们在看到@987654325 时倾向于这样做),它不会导致误报@ 或者如果测试失败是因为它遇到了fail())。

    @Test
    public void shouldThrowExceptionIfValidationFails() throws Exception {
      doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
    
       expectedEx.expect(InvalidException.class);
       expectedEx.expectMessage("Invalid Token");
    
       try{
         // my method call
       }catch(InvalidException e){
         // verify DB save doesn't happens
    
        assertTrue(false);
    
        throw e;
      }
     }
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      相关资源
      最近更新 更多