当它不应该失败时,测试失败了吗?

时间:2017-09-20 11:38:38

标签: java unit-testing junit5

我有这个测试用例:

void loadFromJson() throws Exception
{
    assertThrows(FileNotFoundException.class, ()-> JsonReader.loadFromJson(".json"));
}

这应该抛出一个FileNotFoundException ...它确实......

java.io.FileNotFoundException: .json (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at org.avalin.optaplanner.json.JsonReader.loadFromJson(JsonReader.java:29)

然而我收到了这个错误:

org.opentest4j.AssertionFailedError: Expected java.io.FileNotFoundException to be thrown, but nothing was thrown.

at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:65)
at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:38)
at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:1108)
at org.avalin.optaplanner.test.unitTest.JsonReaderTest.loadFromJson(JsonReaderTest.java:16)

我的测试用例失败了...当它实际抛出请求的异常时,这怎么可能?

1 个答案:

答案 0 :(得分:0)

我不熟悉jupiter.api.AssertThrows,但很容易设置一个忽略/绕过它的测试,并简单地测试代码的lambda方面。

这里的要点是创建一个lambda不运行代码,直到你运行代码。

例如,这里有3个单元测试。 test1test3都会抛出AssertionError,但test2却没有。在AssertThrows()内如何运作,我会让你或其他人回答。

public class TestTest {

   @Test(expected = AssertionError.class)
   public void test1() {
       throw new AssertionError();
   }

   @Test(expected = AssertionError.class)
   public void test2() {
     Runnable r = () -> {throw new AssertionError();};
   }

   @Test(expected = AssertionError.class)
   public void test3() {
     Runnable r = () -> {throw new AssertionError();};
     r.run();
   }
}