Google Guava Collection Test Suite

Did you even implement your own collections for some reason? Collections which implement the Java collection interfaces? Did you ever wonder if there is test suite for collections, which tests the specified collection-interface behavior? When your answer is yes to these questions then you should check out the Google Guava Testlib.

Testing Collections, Ahoi

Testing Collections, Ahoi

The Google Guava Testlib brings a whole test suite which tests the behavior of Set, List and Map implementations. You can specify which features your collections support and then profit from the hundreds of tests Google has written for you.

Getting Started

First we need to get the library. The easiest way to get it is with Maven:

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava-testlib</artifactId>
	<version>13.0</version>
	<scope>test</scope>
</dependency>

After that we can start to write a test suite. There are test-suite builders for this purpose, the most important ones are ListTestSuiteBuilder, SetTestSuiteBuilder and MapTestSuiteBuilder. These builder allow you to create a test-suite according to your needs.
First you specify the collection to be used and the test data with the using-method. Afterwards you can specify what features are implemented by your collection. Here’s an example:

Take a good look into the available constants in CollectionFeature, ListFeature and MapFeature for the features sets to test.
Anyway, BAAAMM! Now I’ve already a huge suite of test running, which cover a lot of dirty details. For example my implementation seems to have issues with the equals method of the returned sub-lists:

Oh Oh

Oh Oh

Setup/Tear-Down, Suppressing Tests

Now the actual tests do run in already written test classes. So what if your collection needs some setup- / tear down code? For example I use the test-suite to test collections which are backed up by a database. That means I need a setup- / tear down phase.
This can be done by providing a runnable for the setup and tear down:

You also can suppress very specific methods of the test suite. This is done by giving the methods which should be suppressed:

Your Own TestData

Perhaps your collection implementation can only hold very specialized elements. In that case you might need to generate the test-items yourself, which are added to the list. Instead of using the Google test data provider, you can use your own. Here’s an example, which tests the collection with a custom type:

Other Types

Above I’ve shown examples for a List implementation. For Sets and Maps it works more or less exactly the same way. Instead of ListSomeThingSomething the classes are called SetSomethingSomething or MapSomethingSomething. Otherwise the same principals apply.

Conclusion

If you ever implement your own Java collections, take a look at the Guava Test lib. It saves you a ton of work!

Tagged on: , ,