gpt4 book ai didi

java - junit 测试 - assertEquals 异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:03 25 4
gpt4 key购买 nike

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

我正在运行的测试。

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

关于java - junit 测试 - assertEquals 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10148101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com