import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; public class InfiniteLoop { @Test public void testResizeLargerImageHighQuality() { int loops = calculateImageRatio(true, 5, 5, 15, 15); assertTrue(loops < 1000); } @Test public void testResizeLargerImageLowQuality() { int loops = calculateImageRatio(false, 5, 5, 15, 15); assertTrue(loops < 1000); } @Test public void testResizeSmallerImageHighQuality() { int loops = calculateImageRatio(true, 25, 25, 15, 15); // infinite loop assertEquals(1000, loops); } @Test public void testResizeSmallerImageLowQuality() { int loops = calculateImageRatio(false, 25, 25, 15, 15); assertTrue(loops < 1000); } private int calculateImageRatio(boolean highQuality, int targetWidth, int targetHeight, int imgWidth, int imgHeight) { int loopcounter = 0; int width; int height; if (highQuality) { // Use the multiple step technique: start with original size, then scale down in multiple passes with // drawImage() until the target size is reached width = imgWidth; height = imgHeight; } else { // Use one-step technique: scale directly from original size to target size with a single drawImage() call width = targetWidth; height = targetHeight; } do { if (highQuality && width > targetWidth) { width /= 2; width = Math.max(width, targetWidth); } if (highQuality && height > targetHeight) { height /= 2; height = Math.max(height, targetHeight); } loopcounter++; } while (loopcounter < 1000 && (width != targetWidth || height != targetHeight)); return loopcounter; } }