0

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.

michjnich
  • 2,796
  • 3
  • 15
  • 31

3 Answers3

2

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

import static org.hamcrest.CoreMatchers.containsString;
Marc Philipp
  • 1,848
  • 12
  • 25
  • I could import this, but it made no difference to the results for some reason. I think it may be to do with the version of JUnit that eclipse is using, and the associated versions of hamcrest. I'm still a little unsure how to find the right classes for things! – michjnich May 24 '18 at 09:23
  • containsString cannot be resolved - must have been removed – Gerry Sep 07 '21 at 15:14
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>
Pradeep
  • 1,192
  • 2
  • 12
  • 30
  • Tried this one too, and had issues with importing the assertThatIllegalArgumentEception class. Pretty sure the issue is (as with the first answer) to do with the versions of JUnit that eclipse is using, even when you select Junit Jupiter. – michjnich May 24 '18 at 09:24
  • Those are static imports, we have to add in eclipse somehow import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; – Pradeep May 24 '18 at 14:05
0

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 :)

michjnich
  • 2,796
  • 3
  • 15
  • 31