- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我最近在一次采访中被问及如何编写一个 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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!