IntelliJ Live Templates with Google Guava

In this screencast, I will explain how to setup IntelliJ live templates with Google Guava, and how to add a bit a Functional Programming to your Java code when using Java 7 or below. The templates used in the video, including the configuration for them, can be found below.

The code to make the filter work, is the following. You’ll have to go to Preferences -> Editor -> Live templates and add a new template there. The following code need to be entered for the filter:

Filter

And the following variables have to be used:

Screen-Shot-2014-03-15-at-22.57.56-600x169

For the transformation, another template needs to be added, similar to the template above.

Transform

With these variables:

Screen-Shot-2014-03-15-at-22.58.18-600x228

If you’ve setup the above, functional programming will become a lot easier, even in Java versions older than Java 8!

A quick introduction to AssertJ

As a developer, you might be familiar with Hamcrest, a declarative rule based object matcher framework. In other words, a testing library which will make your test easy to read. While Hamcrest is a great library, there are some limitations to it’s expressiveness, so looked for a better alternative. Meet AssertJ.

AssertJ is a library which provides a rich set of asserts and a fluent interface to help developers write maintainable tests. Besides that, most of the AssertJ error messages in the case of failing tests are very expressive and helpful, and provide great feedback to the developers in finding out why a test failure occurred.

To setup AssertJ in your project, the only library you’ll need is the assertj-core library. I’ve set up a sample project on Github to help you get started.

To make sure you’re importing the right assertThat method, we’ll be excluding the JUnit method:

exclude-auto-import

To make our lives even easier, we’ll setup an IntelliJ Live Template, which will map the ‘at’ abbreviation to expand to assertThat’s assertion method. This way, we only need to type ‘at’, press , and the right assertThat method will be used, including imports.

live-template

In this example we’ll be testing a small movie catalogue, in which most logic is located in finding the movies, and, in our case, only thrillers:

The code above uses the Guava FluentIterator to filter movies based on certain criteria. In this case a filter will be applied to find only Thrillers. To test this, we write the following AssertJ test:

What happens here, is that for each element in the list of Thrillers, the ‘title’ property is extracted, and an exact match is done on the result of the thrillers result, ie. it should have exactly those 4 elements.

One of the great features of AssertJ is that assertThat is a generic method. This means that your IDE will help you a great deal to know which methods are available to help in testing, since it depends on the type of the object passed to assertThat. To illustrate this, see the following example:

code-completion-list

As you can see here, only the methods which can be applied to a List are shown. When we replace the List with a String

code-completion-error

IntelliJ immediately responds with a compilation error, and when using code completion again, you’ll get the list of methods which are compatible with a String type:

code-completion-string

Besides providing a hints to developers and giving early feedback, AssertJ also enables you to have very readable tests. An example can be seen below:

Here, we extract multiple attributes of a Movie, and we’ll compare them with our actual result. Should a comparison fail, an error is shown:

In this, we expected the movie ‘Se8en’ to be there, but we made an obvious typo, which could be corrected quickly.

I hope this short introduction gave you a impression of what is possible with AssertJ. More examples can be found in the same project or on the AssertJ website. AssertJ provides many more features, like powerful test DSL’s, auto generated asserts for your own types, support for Joda, Guava and Neo4j, and much more.

To find out more, checkout AssertJ and start improving your test code!

Enable Jacoco with Jetty

To enable code coverage in your functional regression test, for example when using Selenium, it’s often handy to measure the code coverage. In our current project we’re using Jacoco for that, since it’s currently the only open source solution which is still maintained and suitable for Java 7.

To enable Jacoco in Jetty, we need to do the following steps:

  1. Download the Jacoco agent
  2. Enable the Java agent in Jetty
  3. Enable the reporting in Maven

Download the Jacoco agent.

The latest version of the Jacoco agent can be downloaded here. In the downloaded jar is another jar, the jacocoagent.jar, which is needed to do online instrumenting of classes.

Enable the Java agent in Jetty.
Once the Jacoco Agent has been downloaded, Jetty needs to be made aware of this. To do this, Jetty needs to be passed the -javaagent parameter. The easiest way to do this is by setting the MAVEN_OPTS environment variable in the following way:

-javaagent:lib/jacocoagent-0.6.3.jar

Alternatively, you can also pass parameters to the -javaagent setting, like this:

-javaagent:lib/jacocoagent-0.6.3.jar=destfile=target/jacoco.exec,append=false,includes=nl.*"

Enable the reporting in Maven

To enable the reporting in Maven the Jacoco Maven plugin is needed. This can be configured in the following way:

Once this has been configured, the report can be created using the jacoco:report task. This will create a jacoco directory in the reporting directory, which is by default the target/site directory. When everything has been set up correctly, a report like the following should be available:

jacocoreport

Register a custom Jackson ObjectMapper using Spring Javaconfig

For a project for a client I’m working on, we are creating a JSON REST interface as a proxy for other systems. Our system collects data and transforms it to be used by the clients of our API. Most of the data we send are Strings, but for a new feature, we are migrating some of our code to Joda Money, a very convenient way of handling basic money operations.

To send our Money data back to our clients, we do a bit of conversion. For this, we use a Jackson Serializer, which looks a bit like this:

However, finding out how to register this class was a bit a hassle, and turned out to be trivial once we found out. To register the Serializer, you’ll need to have a custom ObjectMapper, like the following:

Then we need to register the ObjectMapper in the JavaConfig of our Spring application. This can be done with the following configuration:

And that’s it. Now Jackson is automatically configured to convert all Money objects to cents using the ObjectMapper. I hope this helps for people who need this in the future so that it might save some time!

Gradle: renaming build.gradle to moduleName.gradle

When working with multimodule projects, having many build.gradle files with the same name can be confusing. Gradle provides a way to change this behaviour by using the settings.gradle file, which you can put in your project.

An example settings.gradle file is listed below.

As you can see here, the buildFileName of the main project is now called epub-organizer.gradle instead of build.gradle. For the sub projects (ie the children), the project name is retrieved, replacing all upper case characters with the lower case equivalent, prefixed by a dash, so that epubOrganizer will become epub-organizer. Of course, this is just an example, you can use any naming convention you’d like!

Gradle: displaying artefact locations

Gradle’s output, unlike verbose build tools like Maven, is very terse. In my opinion, a bit too terse. For example, when running gradle jar, this is the output:


:epub-organizer-core:compileJava UP-TO-DATE
:epub-organizer-core:processResources UP-TO-DATE
:epub-organizer-core:classes UP-TO-DATE
:epub-organizer-core:jar UP-TO-DATE
:epub-organizer-dropwizard:compileJava UP-TO-DATE
:epub-organizer-dropwizard:processResources UP-TO-DATE
:epub-organizer-dropwizard:classes UP-TO-DATE
:epub-organizer-dropwizard:jar UP-TO-DATE

BUILD SUCCESSFUL

Total time: 13.752 secs

Okay, that’s nice, looks good, but now what? Where’s my jar? Remembering that it’s produced in build/libs is easy, but a less frequently used task like distZip will produce it’s artefacts in a different location, so you’ll have to remember those locations to. Luckily, Gradle is a very flexible build tool, and with the help of my friend Marcin Erdmann, we came up with the following Gradle script, which you can put in ~/.gradle/init.gradle, or as I did, in my build.gradle file. If you put it in your init.gradle file, please be aware that you’ll have to remove the ‘gradle.’ prefixes.

After each build, the following will now be produced:


:epub-organizer-dropwizard:classes UP-TO-DATE
:epub-organizer-dropwizard:jar UP-TO-DATE

BUILD SUCCESSFUL

Total time: 13.752 secs

Output location: /Users/erikp/User Files/Projects/epub-organizer-gradle/epub-organizer-dropwizard/build/libs/epub-organizer-dropwizard-1.0.jar

Still pretty terse, but quite useful anyway.

Introduction to Hamcrest Collection Matchers

Another post in the series of Hamcrest Matchers, a framework for writing test matcher objects. This week we’ll dive into collections and iterables, and we’ll see how we can use Hamcrest for making those asserts even more readable.

In many software projects I encounter code like the following:

Or, even worse:

The second loses context by not knowning the expected value and the actual value; it knows only that they are not equal.

So, while this above might be a valid asserts, their readability and error feedback can be improved by using a framework like Hamcrest. This can be done in the following way:

In my opinion, this increases readability quite a bit, and makes it easier to maintain tests like this. Check the following piece of code for more examples:

Error messages

Whenever a assertion fails, you get a pretty clear error message, which will help you quickly solve issues you run into. For example, if in the above code example I would have made a wrong assumption, and instead of:

If would have typed:

The following error message would have shown up:

Whereas the the JUnit equivalent:

Would have resulted in the following:

Which would have helped a great deal also, but it’s just that the Hamcrest one is a bit more clear, and a bit more elaborate on the error message.

I hope this helps in picking up Hamcrest and that it helps in writing clear, consistent tests. See you next week!

Introduction to Hamcrest String Matchers

Another week, another blogpost. For those catching on just now, or finding this post using a search engine; I’m writing a series of posts about Hamcrest, a framework for writing test matcher objects, and showing you how to use Hamcrest. While the previous post was about the Core Matchers, the topic of this week is Hamcrest String Matchers.

The Hamcrest String Matchers are the following:
containsString, startsWith, endsWith, equalToIgnoringCase, equalToIgnoringWhitespace, isEmpty, isEmptyOrNull and stringContainsInOrder

Also in this post, I will give an example of all of them in the code block below:

Again, the Hamcrest assertions are very clear, and makes your testcode a easier to read an maintain. Enjoy!

Generate a toString using Guava Objects.toStringhelper with IntelliJ

In IntelliJ it’s possible to generate a toString using Alt+Insert (Windows) or Ctrl+N (Mac). In this dialog, you can choose to use different implementations, like a StringBuffer, a StringBuilder, Apache Commons ToStringBuilder, and more. But if you’re using Google Guava, you can create your own template in IntelliJ. To do so, do the following:

  • Open a class file
  • Press Alt + Insert or Ctrl + N to popup the ‘Generate’ menu
  • Choose toString()
  • Click the button named ‘Settings’
  • Go to the ‘Templates’ tab
  • Create a new template named
  • Add the following in the template:

This template is based on the Apache Commons toStringBuilder, and will generate a consistent toString for you using Google Guava.

Introduction to Hamcrest Core Matchers

In our previous post, we got a small introduction into Hamcrest, a framework for writing test matcher objects, and why you should use them. This post will dive deeper into Hamcrest Matchers. A Matcher is a ‘match’ rule to be defined declaratively. The Hamcrest library comes with numerous matchers included, and it’s of course possible to write your own Matcher.

The topic of this week: the Core Matchers.

The common Matchers of Hamcrest are the following:
is, equalTo, not, anything, instanceOf, any, isA, nullValue, notNullValue, sameInstance, theInstance, isIn, isOneOf and hasToString.

I will give an example of all of them in the code block below:

As you can see, the Hamcrest assertions are very readable, and makes your testcode a bit easier to maintain.

PS: I always wanted to write some posts about Hamcrest, but the thing which really triggered me was the Hamcrest cheat sheet created by Marc Philipp. Be sure to check it out, it’s a great piece of work!