Tay Ray Chuan home archive

Java, redeemed

Thu, 10 Feb 2011 15:55:15 +0800 | Filed under mockito, java, junit

Nowadays I've been using Java pretty heavily. The current CS module I'm taking (data structures and algorithms) requires Java, and it also happens that I'm doing some GAE Java work.

For these, I've been leveraging JUnit 4 and Mockito, and writing code for these have opened my eyes to the more exotic features in Java.

JUnit 4, Custom Annotations

As with my other work, testing is a big thing for me. The IDE that I (and perhaps everyone else) use for Java, Eclipse, integrates tightly with JUnit, so using JUnit for testing was a natural choice.

In JUnit 4, test methods are now marked with the @Test annotation, while the usual setUp and tearDown methods are marked with @Before and @After; previously, you'd have to extend/inherit TestCase.

This neat feature in JUnit 4, known as custom annotations, comes with Java 5, as part of JSR175. A simple annotation might look like this:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

public @interface MyAnnotation {
	int aParam default 0;
}

which would be used thusly:

public class MyClass {
	// used without specifying aParam
	@MyAnnotation
	void method1() {}

	@MyAnnotation(aParam=1)
	void method2() {}
}

You can find a detailed walkthrough here.

As I found out from perusing JUnit's source code, combined with Java's reflection API, this makes for pretty powerful runtime introspection/metadata abilities. We already know that JUnit uses this to discover test methods. For example, this code block shows how JUnit detects annotated methods to validate their signatures..

Mockito, Anonymous classes

While working with GAE Java, I needed a way to test requests and responses to my servlets. Coming from django, which has the test client, I was sad to find out there was no easy way to do this with GAE's SDK for Java.

Some googling led me to this article, which introduced me to Mockito (and mocking in general. I guess I've only scratched the surface of TDD.)

For me, I only stubbed a small subset of request/response capabilities. Here's a simple example:

The interesting part is the stub for request.getParameter() - we implement the Answer<T> interface and initialize an instance all at once. As I learnt elsewhere, what we've just created is an anonymous class.

Endnote

For all the ire that Java commonly gets, each time I look at it I find it more and more interesting. Next up: Contracts for Java. Although I've yet to examine it, it looks very interesting.

blog comments powered by Disqus