2010-12-01 14 views
1

을 테스트합니다.나는 다음과 같은 검사를

이 테스트에 실패하면 인쇄 할 메시지를 추가하고 싶습니다.

예를 들어

내가 어설 시험을하는 경우, 나는이 메시지를 추가하려면 다음을 수행합니다 :

@Test public void assertFail(){ 
    Assert.fail("This is the error message I want printed."); 
    Assert.assertEquals(true, false); 
} 

두 번째 예는 인쇄해야 "이것은 내가 인쇄하고자하는 오류 메시지입니다.". 첫 번째 예제 메시지 텍스트는 어떻게 설정합니까?

답변

1

나는 쉽게 생각할 수는 없지만, this 남자는 부분적으로 그 주위를 돌아 다니는 것처럼 보입니다.

2

@Rule 주석이 도움이됩니다. 당신의 단위 테스트 클래스에 다음과 같이 STH를 추가

import org.junit.Rule; 
import org.junit.rules.MethodRule; 
import org.junit.runners.model.Statement; 
import org.junit.runners.model.FrameworkMethod; 
import org.junit.internal.runners.model.MultipleFailureException; 
... 
@Rule 
public MethodRule failureHandler = new MethodRule() 
{ 
    @Override 
    public Statement apply(final Statement base, FrameworkMethod method, Object target) 
    { 
     return new Statement() 
     { 
      @Override 
      public void evaluate() throws Throwable 
      { 
       List<Throwable> listErrors = new ArrayList<Throwable>(); 
       try 
       { 
        // Let's execute whatever test runner likes to do 
        base.evaluate(); 
       } 
       catch (Throwable testException) 
       { 
        // Your test has failed. Store the test case exception 
        listErrors.add(testException);       
        // Now do whatever you need, like adding your message, 
        // capture a screenshot, etc., 
        // but make sure no exception gets out of there - 
        // catch it and add to listErrors 
       } 
       if (listErrors.isEmpty()) 
       { 
        return; 
       } 
       if (listErrors.size() == 1) 
       { 
        throw listErrors.get(0); 
       } 
       throw new MultipleFailureException(listErrors); 
      } 
     }; 
    } 
}; 

대신 listErrors에있는 모든 예외를 수집 당신은 추가 메시지와 함께 예외 testException을 포장하고 그냥 던지는 고려할 수 있습니다.

+0

해결 방법임을 입증하기 위해 노력하고 있습니다. 감사. – KevinO

+0

@KevinO 나는 한 번 규칙 (테스트 실패 후 스크린 샷)과 비슷한 것을했다. 관심이 있으시면 제 솔루션을 제공 할 수 있습니다. 그러나 예외 처리 방법을 잘 모르겠습니다. 따라서 솔루션을 공유하면 기쁩니다. –

+0

ExpectedException을 사용하여 junit 실패 메시지를 추가하는 데 실패했습니다. – KevinO

1

테스트의 이름을 지정하여 테스트의 내용을 분명히하는 것이 좋습니다. 따라서 일부 테스트가 실패하면 문제가 무엇인지 알려줍니다. 여기에 ExpectedException 규칙을 사용하는 예제입니다 : ExpectedException에 대한 자세한 내용은

@RunWith(JUnit4.class) 
public class CalculatorTest { 
    @Rule 
    public ExpectedException exception = ExpectedException.none(); 

    @Test 
    public void divisionByZeroShouldThrowArithmeticException() { 
    Calculator calculator = new Calculator(); 

    exception.expect(ArithmeticException.class); 
    calculator.divide(10, 0); 
    } 
} 

, 볼이 this article

1

대신의 JUnit에 내장 된 예외 처리 메커니즘의 catch-exception을 사용하고자하는 경우 the ExpectedException JavaDoc, 당신의 문제가 될 수 있습니다 쉽게 해결됨 :

catchException(myObj).doSomethingExceptional(); 
assertTrue("This is the error message I want printed.", 
      caughtException() instanceof ArithmeticException);