测试失败,而它不应该失败?



我有这个测试柜:

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)

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

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

这里的要点是创建lambda不运行代码,直到您,er,运行代码。

因此,以下是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();
   }
}

相关内容

最新更新