0

我有一个 Junit(5) 测试用例,它在变量超出范围时寻找异常,并为此引发 IllegalArgumentException。

@Test
void testOutOfBoundsException() {
    Foo f = new Foo();

    IllegalArgumentException e = assertThrows(
            IllegalArgumentException.class, 
            () -> {
                f.checkVal(10);
                }
    );
    assertThat(e, hasMessageThat(containsString("You must enter a number between 0 and")));
}

我得到错误

The method containsString(String) is undefined for the type FooTest

我已经为 JUnit 和 hamcrest 尝试了许多不同的导入语句,但我似乎无法让它工作。

4

3 回答 3

1

您必须containsStringorg.hamcrest.CoreMatchers类添加静态导入:

import static org.hamcrest.CoreMatchers.containsString;
于 2018-05-24T06:47:07.373 回答
0

感谢那些发布答案的人。

最后我发现我可以简单地做到这一点:

IllegalArgumentException e = assertThrows(
        IllegalArgumentException.class, 
        () -> {
            f.checkVal(10);
            },
            <exception message>); 

所以我不需要第二部分:)

于 2018-05-24T09:21:44.033 回答
0

You can simply use like below instead :

  assertThatIllegalArgumentException().isThrownBy(() -> { 
  f.checkVal(10); 
  }) .withMessage("You must enter a number between 0 and");

you might need assertj-core :

    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.8.0</version>
        <scope>test</scope>
    </dependency>
于 2018-05-23T22:07:30.103 回答