gpt4 book ai didi

java - @Test(expected = Exception.class) 或 Assertions.assertThrows(...) 或assertThatThrownBy(..) 推荐哪一个?

转载 作者:行者123 更新时间:2023-11-30 01:57:43 24 4
gpt4 key购买 nike

我正在使用 JUnit 4.12

<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>1.0.5</version>
<scope>test</scope>
</dependency>

我想知道最推荐使用哪一个@Test(expected = Exception.class)Assertions.assertThrows(...)

最佳答案

使用 JUnit 4.12,有多种方法可以测试代码是否出现预期异常。

try catch

我们可以简单地使用Java的try-catch。

@Test
public void testInvalidData() {
prepareTestData();

try {
userService.fetchUser(1234);
Assert.fail("IllegalArgumentException not thrown");
} catch (IllegalArgumentException expected) {
}
}

每当我们使用这种方法时,我们都必须确保调用Assert.fail(...),以防未抛出预期的异常。

注释属性

正如您已经提到的,@Test 有一个属性来声明预期的异常。

@Test(expected = IllegalArgumentException.class)
public void testInvalidData() {
prepareTestData();

// should throw IllegalArgumentException
userService.fetchUser(1234);
}

如果测试方法抛出异常,则测试为绿色。如果测试方法未引发异常或引发不同的异常,则测试为红色。

这有一个很大的缺点:我们无法弄清楚哪条指令抛出了 IllegalArgumentException。如果 prepareTestData(); 抛出异常,则测试仍然是绿色的。

规则预期异常

JUnit 4 包含内置规则 ExpectedException。 (请记住,JUnit 5 使用扩展而不是规则)

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

@Test
public void testInvalidData() {
prepareTestData();

thrown.expect(IllegalArgumentException.class);
userService.fetchUser(1234);
}

这种方法类似于 try-catch 和 @Test(expected = ...),但我们可以控制从哪个点开始出现异常。

断言抛出

AssertJ 和 JUnit 5 提供了断言特定代码块引发特定异常的方法。

@Test
public void testInvalidData() {
prepareTestData();

Assertions.assertThrows(IllegalArgumentException.class, () -> {
userService.fetchUser(1234);
});
}

Assertions.assertThrows 还返回异常对象以执行进一步的断言,例如断言消息。

摘要

我尝试尽可能频繁地使用 assertThrows,因为测试代码变得可读且灵活。但如果使用得当,所有其他提到的方法也是有效的。

关于java - @Test(expected = Exception.class) 或 Assertions.assertThrows(...) 或assertThatThrownBy(..) 推荐哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828270/

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