2017-09-22 5 views
0

Je voudrais savoir comment je peux écrire un test unitaire pour obtenir le bloc catch pour la méthode suivante. Le FOM.create (données) est une méthode statique.Comment tester l'exception est lancée avec 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); 
     } 
    } 

Actuellement ceci est mon test unitaire, mais il ne touche pas le bloc 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

où est ce getUpdatedJWTToken dans votre code? – Plog

Répondre

0

Vous pouvez vérifier si throwable exception exception n'a pas pris avant le test unitaire. Dans votre cas, vous ne pouvez pas vérifier UnsupportedEncodingException mais pouvez vérifier IllegalStateException.

doit de test unitaire ressemble à:

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

si vous voulez vérifier UnsupportedEncodingException vous devez tester FOM.create(data) méthode

0

Vous pouvez utiliser JUnit s règle d'exception comme ceci:

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(); 
    } 
}