JUnit可以模拟OutOfMemoryErrors吗?

uck*_*man 2 java testing junit unit-testing out-of-memory

我有一种尝试调用内存中图像转换器的方法,如果失败,则尝试在磁盘上进行图像转换.(内存中的图像转换器将尝试分配图像的第二个副本,因此如果原始图像非常大,我们可能没有足够的内存.)

public BufferedImage convert(BufferedImage img, int type) {
  try {
    return memory_converter.convert(type);
  }
  catch (OutOfMemoryError e) {
    // This is ok, we just don't have enough free heap for the conversion.
  }

  // Try converting on disk instead.
  return file_converter.convert(img, type);
}
Run Code Online (Sandbox Code Playgroud)

我想为JUnit编写单元测试来运行每个代码路径,但是运行JUnit并且用足够少的堆来强制执行它是不方便的OutOfMemoryError.有没有办法模拟OutOfMemoryErrorJUnit内部?

在我看来,我可以创建一个假子类,BufferedImage它会OutOfMemoryError在第一次调用内存转换器调用的方法时抛出,但随后会在后续调用中正常运行.不过,这似乎是一种黑客行为.

dty*_*dty 6

你应该嘲笑你的转换器,而不是使用真实的转换器.

一旦你这样做,你只需让你的模拟库在convert()调用方法时抛出一个新的OOME .

例如,使用JMock,您可以这样做:

allowing(mockConverter).convert(with(any(int.class)));
will(throwException(new OutOfMemoryError()));
Run Code Online (Sandbox Code Playgroud)