junit testing - assertEquals for exception

后端 未结 5 961

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:57

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

提交回复
热议问题