gpt4 book ai didi

java - JUnit 4 预期异常类型

转载 作者:IT老高 更新时间:2023-10-28 20:54:16 29 4
gpt4 key购买 nike

我正在尝试对其他人编写的代码进行 JUnit 测试,但我不知道如何测试异常,因为异常似乎缺少类型。

public Pirate(String name, int initialGold) throws Exception {
if(initialGold < 0)
throw new Exception("Init Gold must be >= 0");
this.name = name;
this.numGold = initialGold;
this.health = Pirate.DEFAULT_HEALTH;
this.isCursed = false;
}

我的 JUnit 代码片段:

@Test
public static void constructorTest() throws Exception{
rodgers = new Pirate("Dread Pirate Rodgers", 10000);
assertEquals("Dread Pirate Rodgers" , rodgers.getName());
assertEquals(10000, rodgers.getNumGold());
assertEquals(100, rodgers.getHealth());
assertEquals(false, rodgers.getIsCursed());
}

@Test()
public static void exceptionTest() throws Exception{
rodgers = new Pirate("Dread Pirate Rodgers" , -100);

}

我知道我需要在 test 的括号中加上 expected =(某种类型的异常),但我对异常类型一无所知。

最佳答案

在 JUnit 4.7 中实际上有一个 @Test(expected=Xyz.class) 的替代方法,使用 RuleExpectedException

在您的测试用例中,您声明了一个带有 @Rule 注释的 ExpectedException,并为其分配了默认值 ExpectedException.none()。然后在您期望异常的测试中,将该值替换为实际的期望值。这样做的好处是无需使用丑陋的 try/catch 方法,您可以进一步指定异常中的消息是什么

@Rule public ExpectedException thrown= ExpectedException.none();

@Test
public void myTest() {
thrown.expect( Exception.class );
thrown.expectMessage("Init Gold must be >= 0");

rodgers = new Pirate("Dread Pirate Rodgers" , -100);
}

使用此方法,您可以测试通用异常中的消息是否是特定的。

添加使用 ExpectedException 的另一个优点是您可以在测试用例的上下文中更精确地确定异常的范围。如果您仅在测试中使用 @Test(expected=Xyz.class) 注释,则 Xyz 异常可以在测试代码中的任何位置抛出——包括任何测试设置或预断言测试方法。这可能会导致误报。

使用 ExpectedException,您可以推迟指定 throw.expect(Xyz.class) 直到任何设置和预断言之后,就在实际调用被测方法之前。因此,您可以更准确地确定由实际方法调用引发的异常,而不是任何测试夹具本身。

JUnit 5 注意:

JUnit 5 JUnit Jupiter 已完全删除 @Test(expected=...)@RuleExpectedException。它们被新的 assertThrows() 所取代,这需要使用 Java 8 和 lambda 语法。 ExpectedException 仍然可用于 JUnit 5 到 JUnit Vintage。此外,JUnit Jupiter 还将通过使用 junit-jupiter-migrationsupport module 继续支持 JUnit 4 ExpectedException。 ,但前提是您添加了 @EnableRuleMigrationSupport 的附加类级别注释.

关于java - JUnit 4 预期异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723715/

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