Skip to content

Instantly share code, notes, and snippets.

@maripo
Created July 31, 2012 07:30
Show Gist options
  • Save maripo/3214511 to your computer and use it in GitHub Desktop.
Save maripo/3214511 to your computer and use it in GitHub Desktop.
JUnit assertion methods for web designers (assert existence & size of images)
package org.maripo.test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Assert;
public class ImageAssert extends Assert
{
static final String ROOT_PATH = "/";
// Assert existence and dimension of an image
public static void assertImageSize(int expectedWidth, int expectedHeight, String imagePath)
{
BufferedImage img = _getBufferedImage(imagePath);
if (expectedWidth!=img.getWidth() || expectedHeight!=img.getHeight())
{
fail("Expected: <"+expectedWidth+", "+expectedHeight+"> but was <"+img.getWidth()+", "+img.getHeight()+"> (" + imagePath + ")");
}
}
// Assert existence and height of an image
public static void assertImageHeight(int height, String imagePath)
{
BufferedImage img = _getBufferedImage(imagePath);
if (height!=img.getHeight())
{
fail("Expected: <" + height + "> but was: <" + img.getHeight() + "> (" + imagePath + ")");
}
}
// Assert existence and width of an image
public static void assertImageWidth(int width, String imagePath)
{
BufferedImage img = _getBufferedImage(imagePath);
if (width!=img.getWidth())
{
fail("Expected: <" + width + "> but was: <" + img.getWidth() + "> (" + imagePath + ")");
}
}
// Assert existence of an image
public static void assertImageExists(boolean exists, String imagePath)
{
boolean result = _getFile(imagePath).exists();
assertEquals(exists, result);
}
public static String getFullPath(String imagePath)
{
if ('/'==imagePath.charAt(0))
return imagePath;
else
return ROOT_PATH + imagePath;
}
private static String getFilePath(String imagePath)
{
return imagePath;
}
private static File _getFile (String imagePath)
{
String fullPath = getFullPath(imagePath);
return new File(getFilePath(fullPath));
}
private static BufferedImage _getBufferedImage(String imagePath)
{
File file = _getFile(imagePath);
if (!file.exists())
{
fail("File " + imagePath + " does not exist");
return null;
}
try
{
BufferedImage img = ImageIO.read(file);
return img;
}
catch (IOException e)
{
e.printStackTrace();
fail("Exception Occured. " + e.getMessage());
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment