2012-04-13 23 views
6

¿Cómo puedo usar assertEquals para ver si el mensaje de excepción es correcto? Se pasa la prueba, pero no sé si coincide con el error correcto o no.prueba de junit - assertEquals para excepción

La prueba que estoy ejecutando.

@Test 
public void testTC3() 
{ 
    try { 
    assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5)); 
    } 
    catch (Exception e) { 
    }   
} 

El método que se está probando.

public static int shippingCost(char packageType, int weight) throws Exception 
{ 
    String e1 = "Legal Values: Package Type must be P or R"; 
    String e2 = "Legal Values: Weight < 0"; 
    int cost = 0; 
     if((packageType != 'P')&&(packageType != 'R')) 
     { 
      throw new Exception(e1); 
     } 

     if(weight < 0) 
     { 
      throw new Exception(e2); 
     }   
     if(packageType == 'P') 
     { 
      cost += 10; 
     } 
     if(weight <= 25) 
     { 
      cost += 10; 
     } 
     else 
     { 
      cost += 25; 
     } 
     return cost;  
} 

}

Gracias por la ayuda.

Respuesta

6
try { 
    assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5)); 
    Assert.fail("Should have thrown an exception"); 
} 
catch (Exception e) { 
    String expectedMessage = "this is the message I expect to get"; 
    Assert.assertEquals("Exception message must be correct", expectedMessage, e.getMessage()); 
} 
+1

Gracias! Simple y ayudó mucho – Meowbits

4

Los assertEquals en tu ejemplo sería comparar el valor de retorno de la llamada al método con el valor esperado, que no es lo que quiere, y por supuesto no va a ser un valor de retorno si el excepción esperada ocurre. Mover los assertEquals al bloque catch:

@Test 
public void testTC3() 
{ 
    try { 
     Shipping.shippingCost('P', -5); 
     fail(); // if we got here, no exception was thrown, which is bad 
    } 
    catch (Exception e) { 
     final String expected = "Legal Values: Package Type must be P or R"; 
     assertEquals(expected, e.getMessage()); 
    }   
} 
+0

No vi su respuesta, volví a trabajar mi código después de leer su respuesta. ¡Gracias! – Meowbits

0

Java 8 solución

Aquí es una función de utilidad que escribí:

public final <T extends Throwable> T expectException(Class<T> exceptionClass, Runnable runnable) 
{ 
    try 
    { 
     runnable.run(); 
    } 
    catch(Throwable throwable) 
    { 
     if(throwable instanceof AssertionError && throwable.getCause() != null) 
      throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();" 
     assert exceptionClass.isInstance(throwable) : throwable; //exception of the wrong kind was thrown. 
     assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected. 
     @SuppressWarnings("unchecked") 
     T result = (T)throwable; 
     return result; 
    } 
    assert false; //expected exception was not thrown. 
    return null; //to keep the compiler happy. 
} 

(taken from my blog)

utilizarlo como sigue:

@Test 
public void testThrows() 
{ 
    RuntimeException e = expectException(RuntimeException.class,() -> 
     { 
      throw new RuntimeException("fail!"); 
     }); 
    assert e.getMessage().equals("fail!"); 
} 

Además, si le gustaría leer algunas razones por las debe no desee assertTrue que el mensaje de su excepción es igual a un valor determinado, consulte la siguiente: https://softwareengineering.stackexchange.com/a/278958/41811

1

funciona perfectamente para mí .

try{ 
    assertEquals("text", driver.findElement(By.cssSelector("html element")).getText()); 
    }catch(ComparisonFailure e){ 
     System.err.println("assertequals fail"); 
    } 

si falla assertEquals ComparisonFailure se harán cargo en

0

Esto es bueno que permite hacer valer excepciones de una manera limpia.

Ejemplo:

// given: an empty list 
List myList = new ArrayList(); 

// when: we try to get the first element of the list 
when(myList).get(1); 

// then: we expect an IndexOutOfBoundsException 
then(caughtException()) 
     .isInstanceOf(IndexOutOfBoundsException.class) 
     .hasMessage("Index: 1, Size: 0") 
     .hasNoCause(); 
Cuestiones relacionadas