InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

JUnit 4.7: Per-Test rules

Posted by Geoffrey Wiseman on Jul 22, 2009

Sections
Development,
Architecture & Design
Topics
Java ,
Extensibility
Tags
JUnit

JUnit 4.7, which has just reached Release Candidate stage, includes a significant new feature: Rules.

Rules are, in essence, another extension mechanism for JUnit, which can be used to add functionality to JUnit on a per-test basis. Most examples of custom runners in earlier versions of JUnit can be replaced by Rules. As described in an earlier blog post about the feature:

In JUnit 3 you could also manipulate the test running process itself in various ways. One of the prices of the simplicity of JUnit 4 was the loss of this “meta-testing”. It doesn’t affect simple tests, but for more powerful tests it can be constraining. The object framework style of JUnit 3 lent itself to extension by default. The DSL style of JUnit 4 doesn’t. Last night we brought back meta-testing, but much cleaner and simpler than before.

In addition to the capability of adding rules, a number of core rules have been added:

  • TemporaryFolder: Allows test to create files and folders that are guaranteed to be deleted after the test is run. This is a common need for tests that work with the filesystem and want to run in isolation.
  • ExternalResource: A pattern for resources that need to be set up in advance and are guaranteed to be torn down after the test runs. This will be useful for tests that work with sockets, embedded servers, and the like.
  • ErrorCollector: Allows the test to continue running after a failure and report all errors at the end of the test. Useful when a test verifies a number of independent conditions (although that may itself be a 'test smell').
  • ExpectedException: Allows a test to specify expected exception types and messages in the test itself.
  • Timeout: Applies the same timeout to all tests in a class.

If you'd like to see an example of a rule in action, here's a test using the TemporaryFolder and ExpectedException rules:

public class DigitalAssetManagerTest {

	@Rule
	public TemporaryFolder tempFolder = new TemporaryFolder();

	@Rule
	public ExpectedException exception = ExpectedException.none();

	@Test
	public void countsAssets() throws IOException {
		File icon = tempFolder.newFile("icon.png");
		File assets = tempFolder.newFolder("assets");
		createAssets(assets, 3);

		DigitalAssetManager dam = new DigitalAssetManager(icon, assets);
		assertEquals(3, dam.getAssetCount());
	}

	private void createAssets(File assets, int numberOfAssets) throws IOException {
		for (int index = 0; index < numberOfAssets; index++) {
			File asset = new File(assets, String.format("asset-%d.mpg", index));
			Assert.assertTrue("Asset couldn't be created.", asset.createNewFile());
		}
	}

	@Test
	public void throwsIllegalArgumentExceptionIfIconIsNull() {
		exception.expect(IllegalArgumentException.class);
		exception.expectMessage("Icon is null, not a file, or doesn't exist.");
		new DigitalAssetManager(null, null);
	}
}

To make rule development easier, a few base classes for rules have been added:

  • Verifier: A base class for rules like ErrorCollector that can turn failing tests into passing ones if a verification check is failed.
  • TestWatchman: A base class for rules that observe the running of tests without modifying the results.

Rules were called Interceptors when they made their first appearance in earlier builds of JUnit 4.7. In addition to the rules, JUnit 4.7 also includes:

  • Some changes to the matchers.
  • Tests that timeout now show the stack trace; this can help to diagnose the cause of the test timing out.
  • Improvements to Javadoc and a few bugs fixed.

More information on these features is available in the JUnit 4.7 release notes.  Hamcrest 1.2 support was listed in earlier release notes, but has been rolled back for this release.

While you're waiting for the final release, you can download the release candidate from github, browse org.junit.rules gear, fill out the survey, read about the deadpooling of Kent Beck's JUnit Max, and wait for user reactions to JUnit 4.7 on blogs, friendfeed and twitter.

TemporaryFolder by Geoffrey Wiseman Posted
Nice. by Jeff Brown Posted
  1. Back to top

    TemporaryFolder

    by Geoffrey Wiseman

    I've written TemporaryFolder-like code lots of times, so I'm definitely looking forward to this. Although, I admit that there are places I'd like more customization -- such as if a temporary folder is needed for some test methods and not others, I'd like the ability to indicate that creation should be deferred. Nothing really critical, though.

    I'm interested to see if this develops into a healthy ecosystem of third-party rules.

  2. Back to top

    Nice.

    by Jeff Brown

    This is very cool stuff for JUnit and a nice advancement for the art of unit testing! I hope the idea spreads.

    For the past two years, I have been thinking about building a similar feature for MbUnit v3 in the form of test "mixins." It hasn't happened yet but maybe in an upcoming release... :-)

Educational Content

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.

Beauty Is in the Eye of the Beholder

Alex Papadimoulis discusses ugly code, where it comes from, how to avoid it, and how to get rid of it.

Architecting Visa for Massive Scale and Continuous Innovation

John Davies examines Visa’s architecture and shows how enterprises have architected complex integrations incorporating Hadoop, memcached, Ruby on Rails, and others to deliver innovative solutions.

Max Protect: Scalability and Caching at ESPN.com

Sean Comerford unveils ESPN.com’s architecture, what components are used and why, and the current changes the website goes through.

The Seven Deadly Sins of Enterprise Agile Adoption

Are there repeated patterns of failure on Enterprise Agile Enablement efforts? Sanjiv and Arlen discuss Seven Deadly Sins to avoid when adopting Agile in an enterprise.

Questions for an Enterprise Architect

Erik Dörnenburg answers: What is Enterprise and Evolutionary Architecture?, discussing 4 issues: Turning strategy into execution, Ensuring conformance, Where do the architects sit? Buying or building?

Wrap Your SQL Head Around Riak MapReduce

Sean Cribbs explains what Map-Reduce and Riak are, why and how to use Map-Reduce with Riak, and how to convert SQL queries into their Map-Reduce equivalents.