31.03.2016 | Andreas Günzel | comment icon 0 Comment

How to unit test hazelcast

Recently I used hazelcast in several projects. Especially in an Application Server environment using the hazelcast JCA connector it is pretty easy to use hazelcast with only a few lines of code. Listing 1 shows how to create a hazelcast queue:

Looks trivial. Unfortunately, Hazelcast.getAllHazelcastInstances() returns an empty set in unit tests. So, what we need to do is to mock our HazelcastFactory somehow.

I would guess the hazelcast developers had the same problem. This is probably the reason why a class named com.hazelcast.test.TestHazelcastInstanceFactory.TestHazelcastInstanceFactory exists. As the package name indicates this class is a test resource and thus not accessible as traditional dependency using maven.

There is a trick to get a working dependency to these resources: Using the classifier tests. A classifier is an attribute of every maven dependency. It allows to distinguish artifacts that were built from the same POM but differ in their content. The classifier is optional and seldom used. A common use case for classifiers is the need to attach secondary artifacts to the project’s main artefact like sources or javadoc.

Listing 2 shows how to include hazelcast test artifact in mavens pom.xml:

The first dependency refers to the default hazelcast artifact. The second dependency references the tests artifact. It is a de facto copy of the first one added property classifier.

Please note that we need to define both dependencies (since these are two different maven artifacts). In addition, this trick does not work out-of-the box for any maven project. It is up to the actual project configuration if there are more artifacts shipped than the “default” one.

Finally, let’s have a look at how a unit test looks like in Listing 3:

Happy Coding,

hazelcast junit maven

Leave a Comment