Assert regex matches in JUnit

前端 未结 9 1223
广开言路
广开言路 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 {
    
        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");
    

提交回复
热议问题