Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 407
Filip Avatar asked Jan 05 '15 14:01

Filip


2 Answers

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);
     }
  };
}
like image 152
Nik Avatar answered Sep 19 '22 22:09

Nik


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.

like image 42
John B Avatar answered Sep 19 '22 22:09

John B