Wednesday, 3 October 2012

JUnit - hamcrest incompatibility

When we're using the latest version of JUnit (4.10) and hamcrest (1.3) together we might come across an unexpected behaviour.

Let's take a look at a simple test:

We might think that this test will fail because of the assertion, but the result is:

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V

That's because the default JUnit has a dependency to hamcrest 1.1 and also the artifact org.junit:junit has some hamcrest classes inside its jar. The hasSize matcher is not present in 1.1.

To avoid this problem we need to declare following dependencies in our project:

We need to use JUnit distribution that doesn't have any hamcrest internals and we need to exclude hamcrest dependency as well. What's interesting, we will not bump into this behaviour unless our assertion throws an error. 

Saturday, 15 September 2012

Manipulating collections with lambdaj

Java is not that nice regarding manipulations on collections even though tasks like iterating happen to us on a daily basis.

To ease the pain a little bit we can use the lambdaj library that allows manipulating collections without using loops.

Here is a simple unit test that shows some of lambdaj API and features
(Person class is a pojo with age and name fields, and implemented hashCode and equals methods):


As you can see the code using lambdaj is much shorter and more readable.

The features of the library go far beyond that, there are many aggregation and filtering functions, as well as grouping, sorting and possibility to invoke a method for each collection's item.

The main drawback is that it's slower than standard iterative approach, so if speed is your concern, you need to watch out. However you can always use it in the unit tests.

Saturday, 7 July 2012

Extending maven with some groovy magic

Maven is very strict regarding its conventions and the build lifecycle. Even though it has a lot of plugins that extend its functionality, it doesn't always do what we want it to do.
(If you want more freedom take a look at gradle)

Writing our own plugin is time consuming but we can easily extend maven capabilities with executing groovy code during the build.
All we need to do is add gmaven plugin into pom.xml.
Let's see an example that will make our maven build tell us which operating system we are using:

When we add the plugin we need to specify in which phase it will be run ('validate') and which goal of the plugin will be invoked ('execute'). Then in the source section we write our groovy code that will be executed. As you can see we have access to the dependencies declared in dependencies section of the pom file.

If we don't want to inline our script we can specify the file that contains it:

Another interesting feature is access to maven variables that can be used in the xml configuration of the build.

The findbugsSettingsDirectory variable is set inside our script and then used in the configuration of findbugs plugin.

Monday, 4 June 2012

Testing legacy code with Mockito spies

When we're working with legacy code, before making any changes we should write unit tests that will prevent us from breaking existing functionality. However most of the time, writing tests for legacy code is not easy.

Let's take a look at a simple example, that will try to show the challenges that we may face:

We have a class that calculates a discount for a customer based on his name and the amount of product that he's buying.

The problem hides in a static method call CustomerService.isImportantCustomer(). In the old code we can see a lot of static methods. Let's say that the one in our example is calling the database.
We need to mock it in order to write a proper unit test.

First of all, we will extract the static call to a separate method:

Refactoring using IDE (extracting methods, renaming etc.) is considered to be safe. Once we did that we can use a nice feature of Mockito - spies. 
If we declare our tested class as a spy, we can mock its method the same way as with standard mocks. The test for our class could look like:

The Mockito API for spies is similar to the one for mocks (the syntax is different for overriding void methods).

Sunday, 13 May 2012

Testing getters and setters with openpojo

Testing getters and setters is a little bit controversial topic. However, if we decide to do it or if we are forced to, we can ease the task with openpojo library.

Generally standard getters and setters can be generated by your IDE but testing them is a manual work - it takes some time and seems to be boring. So if the code was generated, why can't we automate the testing?
openpojo doesn't generate the unit test but it allows to test your POJO with a very small effort.

Let's take a look at an example. We have a Person class which is a POJO with generated getters and setters.


To test it we need to create just one class:

Our class defines which rules openpojo will apply and what tests it will execute. We also specify which package will be tested - if we have a lot of classes we can test them all in one go. In our case we're only testing if  getters and setters exist and if they behaving in a conventional way.
Running the class with any coverage tool will show us that the get and set methods are executed.
There are more rules that we can apply (like checking if there are no public fields, no primitive values etc.). We can write our own rules as well.

Thursday, 19 April 2012

JMS with Spring configured in Java

Handling JMS using standard JMS API is a tedious task - you need to create a lot of boilerplate code.
Spring provides an abstraction layer that eases this pain.
In the following example I'm using ActiveMQ (which needs to be started before running any of the code below) but Spring works with other major JMS implementations as well.

In order to send a JMS message we can use JMS template. Here's our sender that's using it:


Spring beans needs to be configured in a context. Let's define Spring configuration in Java code:


JMS template must have a connection factory with a broker url and a destination (in our case it's a queue).
The XML configuration equivalent would look like:


Java configuration provides not only compile-time checking but in my opinion it is more straightforward and easier to control.
Unfortunately we can't escape XML completely, we need to turn on component scanning so that Spring will read configuration from classes in our package:


The example code that would run the sender:

Apart from the sender we can also create the receiver. One of the solutions is to make him asynchronous by implementing MessageListener interface.


The Spring config looks as follows:


Our receiver is set in the message listener container with the connection factory and the destination.
Receiver is missing the same XML configuration as sender, and the running code is analogical.

Here's the list of maven dependencies:

Monday, 2 April 2012

Testing asynchronous calls with awaitility

Testing asynchronous systems is not an easy task. Let's take a simple example:


We have a class that creates file based on a given file name. The interesting thing is, that it does it asynchronously using a thread pool and returns immediately to the caller.

Let's try to create a test for it. Our first attempt could look like that:


The horrible thing about it is that Thread.sleep() invocation. Test should be fast, making them wait unnecessary is very poor solution. And what if the test sometimes fails because of overloaded hardware? Are we going to sleep even more?

To eliminate unneeded waiting, we may come up with a concept of validator:


We no longer need to sleep for a long time, but the code has been significantly polluted. Of course we can refactor our validator, make it more reusable but why reinvent the wheel? There is a nice and small library - awaitility - that will do the same for us.


In a very expressive way, we achieve the same result. Timeout, polling delay and polling interval are of course configurable.