2017-09-22 1 views
0

다음과 같은 방법으로 catch 블록을 얻으려면 단위 테스트를 작성하는 방법을 알고 싶습니다. FOM.create (data)는 정적 메서드입니다.Junit을 사용하여 예외를 테스트하는 방법

public String getValue(Data data) { 
     try { 
      return FOM.create(data); 
     } catch (UnsupportedEncodingException e) { 
      log.error("An error occured while creating data", e); 
      throw new IllegalStateException(e); 
     } 
    } 

현재이 내 단위 테스트이지만 catch 블록 충돌하지 않습니다 예외가 단위 테스트 전에 잡은하지 않는 경우

@Test (expected = UnsupportedEncodingException.class) 
public void shouldThrowUnsupportedEncodingException() { 
    doThrow(UnsupportedEncodingException.class).when(dataService).getUpdatedJWTToken(any(Data.class)); 
    try { 
     dataService.getValue(data); 
    }catch (IllegalStateException e) { 
     verify(log).error(eq("An error occured while creating data"), any(UnsupportedEncodingException.class)); 
     throw e; 
    } 
} 
+0

처럼

단위 테스트해야 보인다 코드에서이 getUpdatedJWTToken은 어디에 있습니까? – Plog

답변

0

당신은 던질 수있는 예외를 확인할 수 있습니다. 귀하의 경우에는 UnsupportedEncodingException을 확인할 수 없지만 IllegalStateException을 확인할 수 있습니다. 당신은 싶어 UnsupportedEncodingException을 확인하는 경우 FOM.create(data) 방법

0

을 테스트해야한다

@Test (expected = IllegalStateException.class) 
public void shouldThrowIllegalStateException() {  
    dataService.getValue(data); 
} 

당신은 다음과 같이 JUnit을의 예외 규칙을 사용할 수 있습니다 :

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

    @Test 
    public void throwsExceptionWithSpecificType() { 
     thrown.expect(NullPointerException.class); 
     thrown.expectMessage("Substring in Exception message"); 
     throw new NullPointerException(); 
    } 
} 
관련 문제