gpt4 book ai didi

java - 如何编写junit测试用例来测试内存不足错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:28 24 4
gpt4 key购买 nike

我最近在一次采访中被问及如何编写一个 junit 单元测试用例来测试“OutOfMemoryError”,我编写了以下代码:-

public class OutOfMemoryError {
public static void main(String[] args) {
new OutOfMemoryError().throwError();
}

public void throwError() {
List<String> list = new ArrayList<>();
for (int i = 0;; i++)
list.add("1");
}
}

Junit 测试用例:-

public class ExceptionTest {
private OutOfMemoryError outOfMemoryError;

@Before
public void init() {
outOfMemoryError = new OutOfMemoryError();
}

@After
public void tearDown() {
outOfMemoryError = null;
}


@Test(expected = Error.class)
public void testError() {
outOfMemoryError.throwError();
}
}

面试官告诉我Junit测试用例不正确。谁能告诉我正确的写法?

最佳答案

JUnit 可能无法正确处理由 OutOfMemoryErrror 引起的测试失败,因为 JUnit 本身需要(很少但不是没有)堆内存来处理失败。

不幸的是,在 Throwable 处理程序启动之前,JUnit 不会释放对被测对象的引用(仍在 Statement 对象中引用),因此即使是垃圾收集也无济于事。查看 ParentRunner.runLeaf 的来源发生这种情况的地方:

    } catch (Throwable e) {
eachNotifier.addFailure(e);

EachTestNotifier.addFailure然后将

    notifier.fireTestFailure(new Failure(description, targetException));

如果没有剩余的堆内存,Failure::new 将抛出另一个错误,阻止正确的测试失败处理。

回到面试:面试官可能想知道使用 JUnit 无法(可靠地)使用直接方法测试 OutOfMemoryErrors,因为 JUnit 框架的设计不是为了如上所述那样做。面试可能也希望看到类似的解决方法

@Test(expected = Error.class)
public void testError() {
byte[] memoryRequiredByJUnitHandler = new byte[100_000];
try {
outOfMemoryError.throwError();
} catch (Throwable t) {
// free enough heap memory so JUnit can handle exception
memoryRequiredByJUnitHandler = null;
throw t;
}
}

有关更多背景信息,您可能还想看看 this answer to "When to catch java.lang.Error?" .

关于java - 如何编写junit测试用例来测试内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092650/

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