2013-08-21 9 views
2

나는 junit을 단언하기 위해 몇 가지 맞춤 matcher를 쓰고있다. 그들 중 대부분은 TypeSafeMatcher를 확장하므로 세 가지 메서드 만 재정의하면됩니다.사용자 정의 hamcrest 일치 프로그램을 테스트하는 방법은 무엇입니까?

public class NoneConstraintViolationMatcher<T> extends 
    TypeSafeMatcher<Set<ConstraintViolation<T>>> { 

    @Override 
    public void describeTo(Description description) { 
     description.appendText("None constraint violations found"); 
    } 

    @Override 
    protected void describeMismatchSafely(Set<ConstraintViolation<T>> item, 
     Description mismatchDescription) { 
     mismatchDescription. 
      appendText("Unexpected constraint violation found, but got "); 
     mismatchDescription.appendValueList("", ",", "", item); 
    } 

    @Override 
    protected boolean matchesSafely(Set<ConstraintViolation<T>> item) { 
     return item.isEmpty(); 
    } 
} 

제 질문은 테스트하는 방법입니다. 나의 현재 솔루션은

public class NoneConstraintViolationMatcherUnitTests { 

    private NoneConstraintViolationMatcher<Object> matcher = 
     new NoneConstraintViolationMatcher<Object>(); 

    @Test 
    public void returnsMatchedGivenNoneConstraintViolations() throws Excetpion { 
     assertTrue(matcher.matches(.....)); 
    } 

    @Test 
    public void returnsMismatchedGivenSomeConstraintViolations() throws Excetpion { 
     assertThat(matcher.matches(.....), is(false)); 
    }   

    @Test 
    public void returnsConstraintViolationsFoundWhenMismatched() 
     throws Exception { 

     StringBuilder out = new StringBuilder(); 
     //I don't find anything could be used to assert in description 

     StringDescription description = new StringDescription(out); 

     matcher.describeMismatch(..someCvx, description); 

     assertThat(out.toString(), 
      equalTo("Unexpected constraint violation found, but got ")); 
    } 
} 

내 마음에 오는 또 다른 방법은 JUnit 테스트를 작성하고 @Rule ExpectedException을 (handleAssertionError true로 설정하여) 사용이다.

당신은 어떻게 matcher를 테스트합니까? 미리 감사드립니다.

답변

2

일치 기능을 테스트하기 위해 assertThat을 사용하고 있습니다.

@Test 
public void returnsMatchedGivenNoneConstraintViolations() throws Excetpion { 
    assertThat(someObject, matcher); 
} 

@Test 
public void returnsMismatchedGivenSomeConstraintViolations() throws Excetpion { 
    assertThat(someObject, not(matcher)); 
} 
+0

응답 해 주셔서 감사합니다. 이 솔루션을 사용하여 설명을 쉽게 테스트 할 수 있습니까? – Hippoom

0

설명을 테스트하는 방법에 대한 후속 질문에 답하려면 필자는 필요한 경우 해당 내용을 볼 수 없습니다. 나는 충분한 중요한 검증이 적절한 예외가 발생하고 있다는 점이다이

@Test(expected=Exception.class) 
public void returnsConstraintViolationsFoundWhenMismatched() { 
    // Use the matcher in a way that causes an exception to be thrown 
} 

처럼 returnsConstraintViolationsFoundWhenMismatched 테스트를 작성하는 것이 좋습니다. 실제 메시지의 내용을 테스트하고 테스트 스위트에 어떤 가치도 추가하지 않습니다. Hamcrest 도서관이 당신이 묘사에 추가 한 텍스트로 옳은 일을하고 있다고 믿을 수 있습니다.

+1

설명을 테스트하고 싶은 상황이 있습니다. 이는 컬렉션의 내용을 확인하고 불일치만을보고하기 때문입니다. 더 구체적으로 말하면, 생성 된 텍스트 대신 설명의 논리 (예 : 루프 및 조건)를 확인하려고합니다. 로직은'matchesSafely' 메소드의 로직과 일치해야하지만 Java에서 로직 코드를 재사용하는 것은 그리 간단하지 않습니다. –

+0

일치하는 로직과 설명 생성이 겹치는 경우 Hamcrest matcher 클래스에 private 메소드를 작성하여 코드를 재사용 할 수 있습니다. 그런 다음 일치 프로그램을 테스트하여 설명을 생성하는 논리를 암시 적으로 테스트합니다. –

+0

미안하지만 논리가 같다고 말하면 루프와 조건의 시체가 아니라 조건을 의미합니다. 예를 들어'matchesSafely'는'if (A) false를 반환합니다; (B) false를 반환하면; true를 반환하고,'describeTo'는'if (A) description.appendText ("A"); if (B) depscription.appendText ("B");'. 나는 Template Method Pattern이 여기에 맞을 것이라고 생각하지만 Java (Java 8 이전)에서는 꽤 장황하다. –