junit报assertexception,junit测试-assertEquals为异常

这篇博客探讨了如何在JUnit测试中确保抛出的异常消息与预期相符。通过修改测试代码,使用`Assert.assertEquals()`来比较捕获到的异常消息与预期错误消息,可以验证方法在遇到非法参数时是否抛出了正确的异常。示例代码展示了如何在测试`Shipping.shippingCost()`方法时检查'PackageType'和'Weight'的合法性。
摘要由CSDN通过智能技术生成

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.

解决方案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() );

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值