Fred van den Driessche

testing optional maps

Last month Tom wrote about Optional Maps, a simple way of avoiding null pointers when dealing with maps in Java. They’re especially useful when more often than not the look-up key is not present in the map. Here I’m going to talk briefly about testing the immutable variant of the optional map.

in the test chamber

The contract defined by the Map interface and its semantics are somewhat non-trivial. Testing that each feature of the interface is fully tested would probably need testing itself. Fortunately for us the decent folk over at Google behind the Guava libraries have included their test library, guava-testlib, as part of the release. The test library contains test suite builders for all types of collections which create suites containing thousands of test-cases covering the expected features of the collection.

Below is the test suite builder used to test our immutable optional map. We supply a generator to supply instance of the type under test along with the features that we expect of the type and list of any specific test cases that should be ignored.

The instance generator is shown next. There are a few methods to implement but they’re all very simple. The most important is the create method which is where the business of actually creating an instance for testing is done.

Three test-cases are suppressed above. They all expect null to be returned when a missing key, null or a key of wrong type is used to access the map. For the OptionalMap absent is expected rather than null so in place of the suppressed tests we add three equivalents of our own which expect absent to be returned. The test-cases are added directly to the test class defining the suite and the class added to the suite itself: suite.addTestSuite(ImmutableOptionalMapTest.class)

work safe, work smart

The end result is that the suite runs an amazing 1684 test-cases against the map. Since ImmutableOptionalmap forwards directly to Guava’s ImmutableMap, and therefore it’s that class that’s mainly under test, it’s not particularly surprising that all the cases pass. Overall, being able to create test suites so easily is extremely useful: I wouldn’t want to write all those cases myself.

blog comments powered by Disqus