Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert regex matches in JUnit

Tags:

java

regex

junit

Ruby's Test::Unit has a nice assert_matches method that can be used in unit tests to assert that a regex matches a string.

Is there anything like this in JUnit? Currently, I do this:

assertEquals(true, actual.matches(expectedRegex));
like image 640
Josh Glover Avatar asked Dec 14 '11 13:12

Josh Glover


2 Answers

If you use assertThat() with a Hamcrest matcher that tests for regex matches, then if the assertion fails you'll get a nice message that indicates expected pattern and actual text. The assertion will read more fluently also, e.g.

assertThat("FooBarBaz", matchesPattern("^Foo"));

with Hamcrest 2 you can find a matchesPattern method at MatchesPattern.matchesPattern.

like image 107
pholser Avatar answered Oct 13 '22 12:10

pholser


No other choice that I know. Just checked the assert javadoc to be sure. Just a tiny little change, though:

assertTrue(actual.matches(expectedRegex));

EDIT: I have been using the Hamcrest matchers since pholser's answer, check that out too!

like image 44
Miquel Avatar answered Oct 13 '22 13:10

Miquel