我正在从TestNg切换到JUnit。我需要将预期的异常消息与预定义的正则表达式进行匹配,例如下面的TestNg代码:
@Test(expectedExceptions = SomeClass.class, expectedExceptionsMessageRegExp = "**[123]regexExample*")
public void should_throw_exception_when_...() throws IOException {
generatesException();
}
效果很好,但是我无法在JUnit中实现相同的行为。我想出了以下解决方案:
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void should_throw_exception_when_...() throws IOException {
expectedEx.expect(SomeClass.class);
expectedEx.expectMessage("**[123]regexExample*");
generatesException();
}
但是方法
expectedEx.expectMessage("**[123]regexExample*");
不支持正则表达式,我需要为其提供确切的硬编码消息。我已经看到可以通过为Matcher提供该方法来实现,但是我不确定如何正确地做到这一点。有什么好的方法吗?
最佳答案
怎么样...
@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);
}
};
}