Assert regex matches in JUnit

前端 未结 9 1216
广开言路
广开言路 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 01:51

    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!

    0 讨论(0)
  • 2020-12-13 02:00

    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.

    0 讨论(0)
  • 2020-12-13 02:02

    A matcher similar to Ralph's implementation has been added to the official Java Hamcrest matchers library. Unfortunately, it's not yet available in a release package. The class is on GitHub though if you want a look.

    0 讨论(0)
  • 2020-12-13 02:03

    Because I was also looking for this functionality, I have started a project on GitHub called regex-tester. It's a library that helps ease testing regular expressions in Java (only works with JUnit currently).

    The library is very limited right now, but it does have a Hamcrest matcher that works like this

    assertThat("test", doesMatchRegex("tes.+"));
    assertThat("test", doesNotMatchRegex("tex.+"));
    

    More about how to use regex-tester is here.

    0 讨论(0)
  • 2020-12-13 02:06


    it's not JUnit but here is another way with fest-assert :

    assertThat(myTestedValue).as("your value is so so bad").matches(expectedRegex);
    
    0 讨论(0)
  • 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]+$"));
    
    0 讨论(0)
提交回复
热议问题