2017-04-03 1 views
4

예외 리턴 코드를 테스트하고 싶습니다.JUnit 4로 사용자 정의 예외의 오류 코드를 테스트하십시오.

class A { 
    try { 
    something... 
    } 
    catch (Exception e) 
    { 
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e); 
    } 
} 

그리고 해당 예외 : 여기 내 생산 코드

class MyExceptionClass extends ... { 
    private errorCode; 

    public MyExceptionClass(int errorCode){ 
    this.errorCode = errorCode; 
    } 

    public getErrorCode(){ 
    return this.errorCode; 
    } 
} 

내 단위 테스트 : 간단한

public class AUnitTests{ 
    @Rule 
    public ExpectedException thrown= ExpectedException.none(); 

    @Test (expected = MyExceptionClass.class, 
    public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception { 
     thrown.expect(MyExceptionClass.class); 
     ??? expected return code INTERNAL_ERROR_CODE ??? 

     something(); 
    } 
} 
+0

가능한 복제에 대한 (expected = MyExceptionClass.class) 선언이 필요하지 않습니다 http://stackoverflow.com/questions/42374416/junit-right-way-of-test-expected-exceptions) –

+0

나는 그것을 할 수있는 좋은 방법을 찾고있다. 시도/catch 괜찮아요하지만 더 많은 코드 라인을 의미합니다. 그건 내 관점에서 읽을 추한 ... – Guillaume

+0

제 대답을 확인하십시오,이 접근법이 당신을 도울 것입니다. –

답변

5

: 당신이 필요로하는 모든 것입니다

@Test 
public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception { 
    try{ 
    whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();  
    fail("should have thrown"); 
    } 
    catch (MyExceptionClass e){ 
    assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE)); 
    } 

여기 :

당신이을 원하는대로 당신이 하지 않으려
  • 당신이 특정 catch 블록을 입력을 원하는 것을 알고 그것의 일부 속성을 확인하기 위해, 특정 예외을 기대; 이 방법은 다른 예외가 발생하는 경우, JUnit을 오류로 어쨌든
2

당신은 그것을 사용하여 확인할 수 있음을보고합니다 - 전화하면 다른 검사가 필요하지 않습니다

  • 가 발생하지 않는 경우에 따라서 당신은 단순히 실패 hamcres 당신이 당신의 종속성 hamcrest 정규를 추가해야합니다 Matcher

    thrown.expect(CombinableMatcher.both(
          CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class))) 
          .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123)))); 
    

    주를받을만큼 thrown.expect 과부하와 같이 정합. JUnit에 포함 된 핵심 일치는 충분하지 않습니다.

    아니면 CombinableMatcher 사용하지 않으려면 : 또한

    thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class)); 
    thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123)); 
    

    을, 당신은 (@Test 주석 [테스트 예상 예외 JUnit을 올바른 방법]의

  • +0

    니스! 고맙습니다! – Guillaume

    관련 문제