containsString is undefined

1.2k Views Asked by At

I have a Junit(5) test case that's looking for an exception when a variable is out of bounds, and I raise an IllegalArgumentException for it.

@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")));
}

I get the error

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

I've tried a number of different import statements for JUnit and hamcrest, but I simply can't seem to get this to work.

3

There are 3 best solutions below

2
On

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>
2
On

You have to add a static import for containsString from the org.hamcrest.CoreMatchers class:

import static org.hamcrest.CoreMatchers.containsString;
0
On

Thanks to those who posted answers.

In the end I found I could simply do this:

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

So I didn't need the second part :)