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.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
3.4 JUnit - Exceptions Test To test if the code throws a desired exception, use annotation @Test(expected = exception. class) , as illustrated in the previous example.
Throws returns the exception that's thrown which lets you assert on the exception. var ex = Assert. Throws<Exception>(() => user. MakeUserActive()); Assert.
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() );
}
The assertEquals in your example would be comparing the return value of the method call to the expected value, which isn't what you want, and of course there isn't going to be a return value if the expected exception occurs. Move the assertEquals to the catch block:
@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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With