junit测试-断言assertEquals [英] junit testing - assertEquals for exception

查看:1012
本文介绍了junit测试-断言assertEquals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在运行的测试.

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

正在测试的方法.

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

}

感谢您的帮助.

推荐答案

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

这篇关于junit测试-断言assertEquals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆