ProgramingTip

JUnit에서 정규식 일치 지정

bestdevel 2020. 11. 3. 08:20
반응형

JUnit에서 정규식 일치 지정


Ruby는 정규식이 있는지 확인하기 위해 단위 테스트에서 사용할 수 Test::Unit있는 멋진 assert_matches방법이 있습니다.

JUnit에 이와 같은 시스템이 있습니까? 현재 나는 이것을한다 :

assertEquals(true, actual.matches(expectedRegex));

정규식 일치를 assertThat()하는 Hamcrest 와 함께 사용 하는 경우 어설 션이 실패하면 예상 패턴과 실제 텍스트를 매처 와 함께 사용 하는 경우 . 주장은 또한 더 유창하게 읽을 것입니다.

assertThat("FooBarBaz", matchesPattern("^Foo"));

내가 아는 다른 선택은 없습니다. 확인하기 위해 javadoc 주장 을 확인했습니다. 하지만 약간의 변화가 있습니다.

assertTrue(actual.matches(expectedRegex));

편집 : 나는 pholser의 대답 이후로 Hamcrest 매처를 사용하고 있습니다.


Hamcrest를 사용할 수 있도록 자신만의 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);
    }
}

용법

import org.junit.Assert;


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

Hamcrest 및 jcabi-matchers를 사용할 수 있습니다 .

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

자세한 내용은 정규식 Hamcrest Matchers를 참조하세요 .

클래스 경로에 다음 두 가지 방법이 필요합니다.

<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>

이 기능도 있었기 때문에 GitHub에서 regex-tester 라는 프로젝트를 시작했습니다 . Java에서 정규 모드를 쉽게 테스트하는 데 도움이되는 라이브러리입니다 (현재 JUnit에서만 작동 함).

라이브러리는 현재 매우 제한적이지만 이와 같이 작동하는 Hamcrest 매 처가 있습니다.

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

regex-tester를 사용하는 방법에 대한 자세한 내용은 여기에 있습니다 .


랄프 구현과 유사한의 매 처가 공식 자바 Hamcrest 라이브러리 매처 추가 되었습니다 . 안타깝게도 아직 릴리스 패키지에서 사용할 수 없습니다. 보기를 수업 GitHub있습니다 .


Hamcrest에는 org.hamcrest.Matchers.matchesPattern (String regex) 와 같은 대응하는 matcher가 있습니다 .

Hamcrest의 개발이 지연되면서 최신 v1.3을 사용할 수 없습니다.

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

대신 새로운 개발 시리즈를 사용해야합니다 (그러나 2015 년 1 월까지 계속됨 ).

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

또는 더 나은 :

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")
}

테스트 중 :

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

assertj를 사용하는 또 다른 대안. 이 접근 방식은 패턴 객체를 직접 전달할 수 있기 때문에 좋습니다.

import static org.assertj.core.api.Assertions.assertThat;
assertThat("my\nmultiline\nstring").matches(Pattern.compile("(?s)my.*string", Pattern.MULTILINE));


JUnit은 아니지만 fest-assert를 사용하는 또 다른 방법이 있습니다.

assertThat(myTestedValue).as("your value is so so bad").matches(expectedRegex);

참고 URL : https://stackoverflow.com/questions/8505153/assert-regex-matches-in-junit

반응형