Assert regex matches in JUnit

前端 未结 9 1217
广开言路
广开言路 2020-12-13 01:40

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 anythi

相关标签:
9条回答
  • 2020-12-13 02:12

    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");
    
    0 讨论(0)
  • 2020-12-13 02:15

    another alternative using assertj. this approach is nice as it allows you to pass the pattern object directly.

    import static org.assertj.core.api.Assertions.assertThat;
    assertThat("my\nmultiline\nstring").matches(Pattern.compile("(?s)my.*string", Pattern.MULTILINE));
    
    0 讨论(0)
  • 2020-12-13 02:16

    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>
    
    0 讨论(0)
提交回复
热议问题