junit testing - assertEquals for exception

exception, java, junit, junit4

Solution

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

Problem

How can I use assertEquals to see if the exception message is correct? The test passes but I don't know if it hits the correct error or not. The test I am running. ``` @Test public void testTC3() { try { assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5)); } catch (Exception e) { } } ``` The method being tested. ``` 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; } ``` } Thanks for the help.

Original source