测试异常时的单元测试最佳实践

时间:2019-10-11 08:42:41

标签: java android unit-testing junit4

因此,我一直在对android应用程序进行单元测试,尽管在某些情况下我会测试失败的情况,但我并没有按照答案给出的建议(Try catch in a JUnit test来测试它们。

我按照下面的代码显示的方式对其进行测试。答案是建议您在测试方法签名上具有“引发异常”,因为如果它实际上引发了您不希望的异常,它将使测试失败。但是,我尝试使用和不使用这段代码,都失败了。 上面提供的答案也使用“规则”来进行这种测试,因为我需要的所有东西都将它们放在try catch块中,并且实例化是在@Before方法中完成的,因此我没有使用过。

@Test
public void testMethod() {
   try{
   //code that will throw exception
   fail("Exception was not thrown");
   } catch (/* types of exceptions */) {
   //my asserts
   }
}

我追求的是哪种方法被认为是“最佳实践”及其背后的原因。

3 个答案:

答案 0 :(得分:3)

expected批注的@Test属性,用于定义测试用例,以检查是否引发了特定的异常。另外,还有@Rules注释用于更具体的控制和不建议使用的“ try-catch”惯用语。有关示例,请参见thisjunit wiki

@Test(expected = IllegalArgumentException.class)

答案 1 :(得分:2)

由于这是用JUnit4标记的,所以我最好使用@Test批注的预期属性

@Test(expected = NullPointerException.class)

但是,如果需要检查所引发异常的其他属性,则可以使用ExpectedException,它非常强大:

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

@Test
public void whenExceptionThrown_thenRuleIsApplied() {
    exceptionRule.expect(NumberFormatException.class);
    exceptionRule.expectMessage("For input string");
    Integer.parseInt("1a");
}

但是我建议使用JUnit 5,在这里您可以利用Java 8构造,例如传递Lambda进行检查,这使您的代码非常声明和简洁。

关于JUnit 4和JUnit 5的好文章:https://www.baeldung.com/junit-assert-exception

答案 2 :(得分:1)

我个人使用assertThrows并将结果分配给Throwable,以便检查消息。 这样做的原因是,例如,当我需要检查返回IllegalArgument的验证时,可以检查该消息是否为该字段所期望的消息。

@Test
public void testSomething_shouldThrowException() {

  String expectedMessage = "Exception running the method";

  Throwable exception = Assertions.assertThrows(YourException.class, () 
    -> {
      bean.doSomething(dummyRequest);
    });

  Assert.assertEquals(expectedMessage, exception.getMessage());
}