JUnit - expected regular expression of exception message

I am switching from TestNg to JUnit. I need to match the expected exception message with a predefined regular expression, for example, in the following TestNg code:

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

This 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 the expectedEx.expectMessage("**[123]regexExample*"); method expectedEx.expectMessage("**[123]regexExample*"); doesn't support regular expressions, I need to provide it with an exact message with a hard link. I have seen that this can be achieved by providing this method with Matcher, but I'm not sure how to do it right.

Any good way to do this?

+6
source share
2 answers

Sort of...

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

Could you use StringContains Matcher?

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

Unfortunately, the library does not have a regular expression library (of which I know). Numerous people have realized their own.

+4
source

Source: https://habr.com/ru/post/980535/


All Articles