junit testing - assertEquals for exception

后端 未结 5 886

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.

5条回答
  •  伪装坚强ぢ
    2021-02-08 16:47

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

提交回复
热议问题