Assert语句中的正则表达式比较

时间:2014-09-08 16:00:19

标签: java junit testng

junit或testng中是否有可用的库函数可以比较两个字符串长度(如正则表达式)。我有一个可以抛出各种异常的函数,我试图弄清楚如何在一个简单的测试用例中处理所有消息。

1 个答案:

答案 0 :(得分:2)

ExpectedException#expectMessage怎么样?

@Rule ExpectedException expectedException = ExpectedException.none();

@Test public void yourTest() {
  // One overload takes a string to test "contains".
  expectedException.expectMessage("foo");

  // The other takes a Hamcrest matcher. startsWith is a Hamcrest core matcher.
  expectedException.expectMessage(startsWith("Bar"));

  // If you include the latest Hamcrest source, you can use the brand-new
  // MatchesPattern matcher, which is the regex solution you're looking for.
  expectedException.expectMessage(new MatchesPattern(
      new Pattern("Baz.+\[[0-9]+\]")));

  systemUnderTest.doExceptionThrowingCode();
}

请参阅StartsWith的文档或MatchesPattern的新代码(17天之久!)。