2017-09-22 56 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

单元测试必须是这样的:

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

,如果你想检查UnsupportedEncodingException必须测试FOM.create(data)方法

0

您可以使用的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(); 
    } 
}