- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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,有多种方法可以测试代码是否出现预期异常。
我们可以简单地使用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/
我是一名优秀的程序员,十分优秀!