gpt4 book ai didi

java - 如何在 JUnit 测试中使用 ExpectedException 验证生产代码中的断言错误

转载 作者:行者123 更新时间:2023-12-02 03:09:45 25 4
gpt4 key购买 nike

在生产代码中的方法 myMethod 中的某个位置有断言,例如:

public void myMethod(List list1, List list2) {
assert list1.size() == list2.size()
}

和单元测试

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

@Test
public void test() throws Exception {
ex.expect(java.lang.AssertionError.class);
myMethod(Arrays.asList(1, 2), Arrays.asList(1, 2, 3));
}

我希望单元测试能够成功运行,但我收到了 AssertionError。为什么会这样?

最佳答案

假设您使用的是 4.11,则 javadoc of ExpectedException

By default ExpectedException rule doesn't handle AssertionErrors and AssumptionViolatedExceptions, because such exceptions are used by JUnit. If you want to handle such exceptions you have to call handleAssertionErrors() or handleAssumptionViolatedExceptions().

假设使用 -ea 选项启用断言,只需添加调用 handleAssertionErrors()

@Test
public void test() throws Exception {
ex.handleAssertionErrors();
ex.expect(java.lang.AssertionError.class);
myMethod(Arrays.asList(1, 2), Arrays.asList(1, 2, 3));
}
<小时/>

You should no longer need the above in JUnit 4.12 (or in versions 10 and under).

Deprecated. AssertionErrors are handled by default since JUnit 4.12. Just like in JUnit <= 4.10.

This method does nothing. Don't use it.

关于java - 如何在 JUnit 测试中使用 ExpectedException 验证生产代码中的断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244939/

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