2012-04-13 14 views
6

Jak mogę użyć assertEquals, aby sprawdzić, czy komunikat o wyjątku jest poprawny? Test przechodzi, ale nie wiem, czy trafia w odpowiedni błąd, czy nie.junit testing - assertEquals for exception

Test, który prowadzę.

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

Metoda testowana.

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

}

Dzięki za pomoc.

Odpowiedz

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

Dziękujemy! Prosty i bardzo pomógł – Meowbits

4

W assertEquals W przykładzie byłoby porównanie wartości zwracanej przez wywołanie metody do wartości oczekiwanej, co nie jest to, co chcesz, i oczywiście nie będzie wartość zwracaną, jeśli spodziewany wyjątek występuje. Przenieś assertEquals do bloku 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

Nie widziałem twojej odpowiedzi, przerobiłem mój kod po przeczytaniu twojej odpowiedzi. Dziękuję Ci! – Meowbits

0

Java 8 rozwiązanie

Oto funkcja narzędzie, które napisałem:

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)

Użyj go w następujący sposób:

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

Ponadto, jeśli chcesz przeczytać kilka powodów należy nie chcą assertTrue że przesłanie swojej wyjątkiem jest równa określonej wartości, to zobaczyć: https://softwareengineering.stackexchange.com/a/278958/41811

1

działa idealnie dla mnie .

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

jeśli assertEquals nie ComparisonFailure będzie go

0

obsłużyć To jest ładne który pozwala twierdząc wyjątków w czystym sposób.

Przykład:

// 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(); 
Powiązane problemy