如果代码中有任何异常,如何使 Junit 测试用例失败?

How to make a Junit test case fail if there is any exception in the code?

我编写了一个 Junit 测试来对我的代码进行单元测试。当我的代码中出现任何异常时,我希望我的 Junit 测试用例失败。我尝试使用 assert 语句,但即使我的代码出现异常,我的 Junit 测试用例也会通过。请谁能告诉我如何实现这一目标?谢谢。

我强烈建议您只测试您的功能。如果抛出异常,测试将自动失败。如果没有抛出异常,您的测试将全部变为绿色。

但是如果你仍然想编写在异常情况下应该失败的测试代码,请执行以下操作:-

@Test
public void foo(){
   try{
      //execute code that you expect not to throw Exceptions.
   }
   catch(Exception e){
      fail("Should not have thrown any exception");
   }
}

您可以断言全局变量 "excepted" = null 或类似的东西,并将其初始化为等于 catch 块中的某些信息字符串。

如果不进一步编码,以下两个测试都会失败:

@Test
public void fail1() {
    throw new NullPointerException("Will fail");
}

@Test
public void fail2() throw IOException {
    throw new IOException("Will fail");
}

实际上,当代码中抛出异常时,您的测试应该会失败。当然,如果您捕获了这个异常并且没有进一步抛出它(或任何其他异常),测试将不会知道它。在这种情况下,您需要检查方法执行的结果。 示例测试:

@Test
public void test(){
  testClass.test();
}

测试失败的方法:

public void test(){
  throw new RuntimeException();
}

不会通过测试的方法

public void test(){
  try{
    throw new RuntimeException();
  } catch(Exception e){
    //log
  }
}

在 JUnit 4 中,您可以使用 @Test 注释的 expected 属性 显式断言 @Test 应该因给定异常而失败:

  @Test(expected = NullPointerException.class)
  public void expectNPE {
     String s = null;
     s.toString();
  }

参见JUnit4 documentation on it

使用: 最后断言或Assert.assertTrue随心所欲