Assert regex matches in JUnit

前端 未结 9 1237
广开言路
广开言路 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:08

    There is corresponding matcher in Hamcrest: org.hamcrest.Matchers.matchesPattern(String regex).

    As development of Hamcrest stalled you can't use latest available v1.3:

    testCompile("org.hamcrest:hamcrest-library:1.3")
    

    Instead you need to use new dev series (but still dated by Jan 2015):

    testCompile("org.hamcrest:java-hamcrest:2.0.0.0")
    

    or even better:

    configurations {
        testCompile.exclude group: "org.hamcrest", module: "hamcrest-core"
        testCompile.exclude group: "org.hamcrest", module: "hamcrest-library"
    }
    dependencies {
        testCompile("org.hamcrest:hamcrest-junit:2.0.0.0")
    }
    

    In test:

    Assert.assertThat("123456", Matchers.matchesPattern("^[0-9]+$"));
    

提交回复
热议问题