Assert regex matches in JUnit

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!


You can use Hamcrest and jcabi-matchers:

import static com.jcabi.matchers.RegexMatchers.matchesPattern;
import static org.junit.Assert.assertThat;
assertThat("test", matchesPattern("[a-z]+"));

More details here: Regular Expression Hamcrest Matchers.

You will need these two dependencies in classpath:

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-core</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.jcabi</groupId>
  <artifactId>jcabi-matchers</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

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.


You can use Hamcrest, but you have to write your own matcher:

public class RegexMatcher extends TypeSafeMatcher<String> {

    private final String regex;

    public RegexMatcher(final String regex) {
        this.regex = regex;
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("matches regex=`" + regex + "`");
    }

    @Override
    public boolean matchesSafely(final String string) {
        return string.matches(regex);
    }


    public static RegexMatcher matchesRegex(final String regex) {
        return new RegexMatcher(regex);
    }
}

usage

import org.junit.Assert;


Assert.assertThat("test", RegexMatcher.matchesRegex(".*est");

Tags:

Java

Regex

Junit