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?
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);
}
};
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With