Thursday, November 6, 2008

Java and dynamic languages

Dynamic languages (like Ruby, Groovy) are quite popular in nowadays. As for me it's a big challenge for developers to learn and use at least one dynamic language in every day job. Of course, there should be a good reason to do that.

So today I would like to demonstrate some examples how I'm using Groovy to write tests for Java classes I've been developing. What's very interesting that it's possible to combine Java and Groovy code seamlessly within one project (== one jar) and everything works just fine.

Let's start with an example.

Assume, in our project we heavily use image processing class ImageUtils with static methods scaleHighQuality and scaleLowQuality, which perform image scaling. For testing purposes, we've included a bunch of images as resources to our jar. Let's develop test case witch goes through all image resources, scales each image (up or down) to 125x125 pixels with low- and high-quality scaling algorithms.

import org.junit.Test
import java.awt.image.BufferedImage
import javax.imageio.ImageIO

public class ImagesTestCase extends GroovyTestCase {
private void scale( Closure c ) {
URL location = new URL(
getClass().getProtectionDomain().getCodeSource().getLocation(),
""
)

// Enumerate all image resources
new File( location.toURI() ).list().each() { file ->
if( file.toLowerCase() =~ /(png|gif|jpg)$/ ) {
BufferedImage image = ImageIO.read( new URL( location, file ) )
assertNotNull( "Input image is null", image )

BufferedImage transformed = c( image );
assertNotNull( "Transformed image is null", resized )

assertTrue( transformed.getWidth() <= 125 )
assertTrue( transformed.getHeight() <= 125 )
}
}
}

@Test public void testImagesLowQuality() {
scale() { image ->
ImageUtils.scaleLowQuality( image, 125, 125 )
}
}

@Test
public void testImagesHighQuality() {
scale() { image ->
ImageUtils.scaleHighQuality( image, 125, 125 )
}
}
}

Why I'm using Groovy for that?
1) It's much faster to write a test code (simplified syntax)
2) Tests look more accurate and compact (powerful library)
3) Groovy has a bunch of modern features which make development even more pleasant (closures, regular expressions, ...)

I would say, "Developers, keep in touch with dynamic languages!"

No comments: