junit testing - assertEquals异常

Meo*_*its 9 java junit exception-handling exception junit4

如何使用assertEquals查看异常消息是否正确?测试通过,但我不知道它是否达到了正确的错误.

我正在运行的测试.

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

正在测试的方法.

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;       
}
Run Code Online (Sandbox Code Playgroud)

}

谢谢您的帮助.

Mar*_*rvo 10

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() );
}   
Run Code Online (Sandbox Code Playgroud)


Nat*_*hes 5

您的示例中的assertEquals将方法调用的返回值与期望值进行比较,这不是您想要的,当然,如果发生期望的异常,则不会有返回值。将assertEquals移到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());
    }        
}
Run Code Online (Sandbox Code Playgroud)