TAGS :Viewed: 26 - Published at: a few seconds ago

[ JUnit - expected exception message regular expression ]

I'm switching from TestNg to JUnit. I need to match expected exception message with predefined regular expression such as in the following TestNg code:

@Test(expectedExceptions = SomeClass.class, expectedExceptionsMessageRegExp = "**[123]regexExample*")
    public void should_throw_exception_when_...() throws IOException {
        generatesException();
    }

That works fine, but I cannot achieve the same behavior in JUnit. I came up with this solution:

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void should_throw_exception_when_...() throws IOException {
    expectedEx.expect(SomeClass.class);
    expectedEx.expectMessage("**[123]regexExample*");
    generatesException();
}

But method expectedEx.expectMessage("**[123]regexExample*"); does not support regular expressions, I need to provide it with the exact hardcoded message. I've seen this could be achieved by providing that method with Matcher but I'm not sure how to do it properly.

Any good way of doing this?

Answer 1


Could you use the StringContains Matcher?

expectedEx.expectMessage(StringContains.containsString("regexExample"));

Unfortunately, there is not a Regular Expression Matcher in the library (that I know of). Numerous people have implemented their own.

Answer 2


What about something like...

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void test1() throws IOException {
   expectedEx.expect(SomeClass.class);
   expectedEx.expectMessage(matchesRegex("**[123]regexExample*"));
   generatesException();
}

private Matcher<String> matchesRegex(final String regex) {
   return new TypeSafeMatcher<String>() {
     @Override
     protected boolean matchesSafely(final String item) {
        return item.matches(regex);
     }
  };
}