简体   繁体   English

JUnit4预期异常

[英]JUnit4 expected exception

I'm making scenario tests with JUnit4 for a project. 我正在使用JUnit4为项目进行场景测试。

In one of the tests I need to check for an expected exception. 在其中一个测试中,我需要检查预期的异常。 With JUnit4 I do this using the annotation. 使用JUnit4,我使用注释完成此操作。

 @Test(expected=...) 

Now the problem is that underneath the code in the test that throws the exception there's some other annotations I need to check which doesn't get excecuted. 现在的问题是,在测试中抛出异常的代码下面还有一些我需要检查的其他注释哪些不会被激活。 An example given: 举个例子:

   @Test(expected=NullPointerException.class)
     public void nullPointerTest() {
         Object o = null;
         o.toString();
         assertTrue(false);
     }

This tests passes because it gets the nullpointerexception however there's obviously an assertion error with the asserTrue(false) and thus I want it to fail. 这个测试通过是因为它获得了nullpointerexception,但是asserTrue(false)显然存在断言错误,因此我希望它失败。

What's the best way to fix this? 解决这个问题的最佳方法是什么? A solution to this could be the following, but I don't know if this is the correct way to do it. 对此的解决方案可能如下,但我不知道这是否是正确的方法。

@Test
public void nullPointerTest2() {
    boolean caught = false;
    try{
        Object o = null;
        o.toString();
    }
    catch(NullPointerException e)
    {
        caught = true;
    }
    assertTrue(caught);
    assertTrue(false);
}

This second test fails as predicted. 第二次测试失败了。

Consider: 考虑:

@Test(expected=NullPointerException.class)
public void nullPointerTest2() {
  boolean caught = false;
  try{
     Object o = null;
     o.toString();
  }
  catch(NullPointerException e)
  {
    // test other stuff here
     throw e;
  }
}

This allows for additional checks while still taking full advantage of JUnit's built-in exception checking. 这允许进行额外的检查,同时仍然充分利用JUnit的内置异常检查。

Also, I consider the use of @Rule ExpectedException to be a better option that expected in many cases. 此外,我认为使用@Rule ExpectedException是一个更好的选择,在许多情况下是expected

JUnit4 is behaving as expected: when an exception is thrown, execution does not continue. JUnit4的行为与预期一致:抛出异常时,执行不会继续。 So the NullPointerException gets thrown, the test method exits, JUnit4 marks it as passing because you expected an exception. 因此抛出NullPointerException ,测试方法退出,JUnit4将其标记为传递,因为您预期会发生异常。 The code after the null dereference effectively does not exist. null解除引用后的代码实际上不存在。

If you want the behavior of the second test, then what you've written is a good solution. 如果你想要第二次测试的行为,那么你所写的是一个很好的解决方案。 But it's a weird thing to want. 但这是一件奇怪的事情。 It seems to me that you are conflating two different tests. 在我看来,你正在混淆两种不同的测试。 One test should test that an exception is thrown under exceptional circumstances. 一个测试应该测试在特殊情况下抛出异常。 A second test should test whatever the second assertion checks. 第二个测试应测试第二个断言检查。

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

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