I have a method which tries to call an in-memory image converter, and if that fails, then tries to do the image conversion on disk. (The in-memory image converter will try to allocate a second copy of the image, so if the original is very large, we might not have sufficient memory for it.)
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);
}
I'd like to write unit tests for JUnit which exercise each code path, but it's inconvenient to run JUnit with little enough heap to force an OutOfMemoryError. Is there some way to simulate an OutOfMemoryError within JUnit?
It has occurred to me that I could make a fake subclass of BufferedImage that throws an OutOfMemoryError the first time a method called by the in-memory converter is called, but then behaves normally on subsequent calls. This seems like a hack, though.