Unit testing algorithms

In the last weeks, I’ve been improving my computer science knowledge by solving programming problems. Since these problems have multiple solutions, I find myself writing duplicated unit tests. And refactoring these tests is cumbersome (if find&replace doesn’t work).

To make the point clear, I’m going to pick a problem with many possible implementations: sorting an integer array. To solve it, we can do heap sort, insertion sort, merge sort, quick sort, selection sort and so on. In the end, we will have a set of five tests for each test case. If in the future, I’ll come up with a new test case, I’ll have to write five tests to check each implementation. This is far from optimal.

After doing a bit of digging I found a convenient solution to removing the duplication: JUnit5’s @ParameterizedTest and @ValueSource. I had to do a bit of refactoring: I created a new interface that declares the sort method and I made sure that all *sort classes implement the interface properly (you did create one class per implementation, right?). After that, it was just a matter of wiring up the tests.

Cool! 🙂 Before, the unit tests were all over the place and not all implementations had all the corner cases tested. Soon enough, I found that the QuickSort implementation throws StackOverflowError when the input array contains duplicate values. You can find the source code here.

Database integration tests

Did you ever struggle while trying to write integration tests without mocking the third party? I know I did.

I’ve known about Martin Fowler since I was a junior developer. He is one of my favorite technology thought-leaders and I enjoy reading the thought-provoking articles that he publishes on his blog. In this post, I want to expand on his article about the test pyramid, in which he explains the difference between unit tests, integration tests and, UI tests. I’ll expand on the part about integration tests.

I want to show you an easy way to run integration tests against a database. With this goal in mind, I’ve created this java demo project. It illustrates the concept and is useful as a starting point for more complicated applications.

In the past, I would delay writing the integration tests. I dislike the idea of not having any integration tests. Fixing errors at runtime is not something that I want to do in Java. Meanwhile, I didn’t want to invest time on setting up a separate test infrastructure. And tests running against a mocked database, are not testing anything. The options seemed limited:

  • mocking the database interaction layer
  • connecting to an in-memory database
  • connecting to a local/remote test database

Regardless of the option I picked, I always had the feeling that the solution could be more elegant. My hesitation would turn into frustration as the application grew and the tests would become harder to maintain. Recently, I discovered a better option: connecting the tests to a database running in a Docker container.

In my last project, Vlad and Max showed me that using docker containers simplifies running integration tests against a database. No mocking, no complicated infrastructure, no tinkering with configuration files. As long as you can run Docker on the build machine, you can run the tests.

This is the elegant solution that I was looking for:

  • install and configure Docker on the build servers and the developer machines that will run the tests
  • use docker-maven-plugin to build a docker image of the database and start/stop a container based on the image
  • populate the database with the necessary data (use ‘/docker-entrypoint-initdb.d/’ or a database migration tool like flyway)
  • finally, use maven-failsafe-plugin to run the integration tests

I like this approach because the integration tests are portable and easy to debug. If the tests run on my laptop, they will run also on the build machine. If the tests fail on the build machine, the problem will also appear on my laptop.

I also like that the tests are repeatable: the plugin builds the Docker image from scratch before the tests start and removes it after the tests finish.

Finally, I like that this approach is transferable to other types of integration tests. It’s easy to replace the database container with a dockerized REST API (in a move towards contract testing) or with a message queue container.

The demo project is more than a typical “hello world” application. The integration test starts a docker MySQL container and makes a simple SQL query. You will notice that the docker-maven-plugin configuration is more complicated than necessary, given such a simple test. The reason: the code samples that I found online seemed trivial. I wanted to have a “bootstrap” project that I could reuse in real-life projects without the hassle of gluing everything from scratch.

This approach to writing integration tests has opened my eyes to the possibilities that exist today in the QA automation domain. The tools built on top of Docker seem varied enough to accommodate all test types. The number of plausible excuses for not having a proper CI pipeline is getting too low…

JCrete 2018 was amazing

I know it’s after the fact, but I want to share my experience at JCrete2018. I encourage you to join the invite lottery when it opens up in December.

A disclaimer: JCrete overwhelmed me and I am not able to do it justice in this post. The participants were incredibly knowledgeable and I felt humbled many times during the sessions. Initially, I sat through sessions just absorbing new information. Slowly, questions started popping up in my mind, but I was blocked by the fear that I wouldn’t have anything interesting to say. Eventually, my curiosity took over and I had some good chats with some of the big guys (Robert Scholte, Cliff Click, Heinz Kabutz, Ivan Krylov and Chris Newland). It turns out they were approachable and very inspiring.

JCrete lasted for five days and had about four sessions and about two leisure activities per day. It was common for the session discussions to continue during the relax time. If you’re not familiar with the “unconference” concept, I have a friend who was there and explains it well.

Monday’s highlight — Challenges of AOT

I didn’t know anything about AOT compilation, so I went. During the session I realized that the Java ecosystem is vast and the technology behind it is, to say the least, sophisticated. This session made it clear that some smart computer scientists are working on the JVM and the Java language.

I wanted to learn more about this theme and Ivan Krylov recommended this video about JIT.

Tuesday’s highlight — Java mentors

Some time ago I realized the value of having mentors. In this session, we discovered that the mentor has expectations from the mentee: learn, show interest, develop soft skills and act on the previous points. But the mentee also has expectations: code reviews, get in contact with new tools and processes. Another discovery is that finding a mentor is not that hard: just reach out to them and show them your dedication.

Wednesday’s highlight — GDPR

There were three people in the room that had implemented GDPR. The session was focused on the technical implications of applying the law. Basically, it turned out to be a crash course on the subject. The basics are:

  • GDPR applies to you if you handle personal data of individuals (e.g. customers, employees) that are EU citizens.
  • categories like sexual orientation, religion, ethnicity are also considered personal data.
  • the scope of the GDPR responsibility is as broad as possible: you’re even responsible for 3rd parties that process your data.
  • everything needs to be accounted for: clear documentation of data storage, data handling procedures, on-demand/automatic data deletion procedures.
  • opt-ins need to be clear and explicit.
  • everything needs to be audited every year.
  • you need to have a point of contact in one of the EU member states.

Thursday’s highlight — Communication for introverts

I was surprised at the number of people that joined this session. And, judging by the number of people engaged in the conversation, it seems this is a hot topic. We shared useful tips&tricks of how to deal with unexpected work situations. These are just a few:

  • if you get angry, go out and do something physical to consume the anger.
  • start labeling people as green (they have a significant positive impact on your life), yellow (so and so) and red (they hurt you in any way). Get rid of the reds (e.g. switch jobs, end friendships). Be strict about it.
  • it’s the manager’s responsibility to solve many of the issues that appear in the workplace. You don’t need to take it upon yourself to fix them.

Some of the ideas from that session are also in this talk.

Friday’s highlight — Contributing to maven

On the Hackday I went to the session lead by Robert Scholte. He introduced us to contributing to open source by fixing maven defects. It turns out it’s not as hard as it seems:

  • start small: pick a plugin that you’re interested in, but don’t go for the big ones (e.g. compiler, surefire).
  • open the project page and locate the “Issue Management” page and then open up the Jira board for that plugin.
  • pick a simple bug. That’s it.
  • bonus: Robert added a label recently for easy bugs (i.e. up-for-grabs).

JCrete 2018 was marvelous and I hope to go there again in the following years. But I’ll have to join the lottery in December, just like the rest of the mortals 🙂

Maven plugins that I like

I’ve been through a couple of projects until now and I’m noticing that there are a couple of maven plugins that are useful, but are not that famous. I’ll list them below, together with a small explanation of why I find them useful.

Build Number Maven Plugin (org.codehaus.mojo)

Sometimes you want to expose the current build version of your application without necessarily updating the artifact version (when you’re iterating fast and using *-SNAPSHOT). I didn’t get to use this one, but I can image that it would be good to have in a /info endpoint.

Apache Maven Shade Plugin

Sometimes you need to package all your dependencies into a single jar file. If you’re using Spring-Boot, you’ll have an easier life if you use the spring-boot-maven-plugin. Most of the time I use it for small projects, where I want to keep everything compact.

License Maven Plugin (org.codehaus.mojo)

Sometimes you need to add a license header to all the files of your project or you’ll need to pack with you application a file with all the licenses of the 3rd party libraries that you’re using. I wish i would have known about it three years ago when I was updating THIRD-PARTY.txt files manually.

Versions Maven Plugin

Sometimes you want to update the libraries that you’re using to the latest version. This plugin makes managing that update a lot easier. You have good control over the strategy of the version advance. This plugin makes your life easier, assuming you have enough tests to make sure that the update didn’t break your application. I just discovered this plugin and I like that it makes the library update chore a breeze.

Apache Maven Enforcer Plugin

Sometimes you need to make it clear what versions of OS, Java etc the application can be built with (because of incompatibilities). I like it that the set of already-made rules is extensive.

Apache Maven Checkstyle Plugin

Sometimes you need to enforce the codestyle that the team has agreed to. A bonus is that it helps the new members of the team to pick up the code standards immediately. I have a love and hate relationship with this plugin, but overall I’m happy to see the same kind of code everywhere.

OWASP Dependency-Check Plugin

You always want to have an application that is as secure as possible. This plugin allows you to automatically check for the latest reported vulnerabilities. I knew about the OWASP Top Ten for a couple of years and I learned about this plugin 2 months ago. I’ll never stop using it.

One last thing: I’m new at writing posts. If you have any suggestions to make this post more clear, please write a comment.

Java Unconferences/Open-spaces

This year I attended CITCON and then I searched for a similar Java unconference/open-space. I got super lucky to be accepted at JCrete, but that’s another story. The reality is that unconferences are mind-blowing, but a bit hard to find if you don’t know what to look for.

These are the unconferences that I currently know about:

Join one… it’s going to be worth it.

One last thing: I’m new at writing posts. If you have any suggestions to make this post more clear, please write a comment.

Testing JPQL queries straight from Intellij

In my current project, most of the queries are written in JPQL (Java Persistence Query Language). As with any xxx-QL (that eventually gets translated to SQL), it’s cumbersome to do the translation of the xxx-QL to SQL and back. This translation is generally done when you’re creating a new query or trying to debug an existing query. It would be great to be able to send JPQL queries directly to the DB.

One way to do this is to configure the JPA console in IntelliJ IDEA. Note that this feature is only available in the paid Edition.

For those that are in a rush, this is the minimal configuration needed to get the JPA console going. To keep things simple, let’s assume that you have a single module project, called test-jpa:

  1. Add a new data source to the project (View | Tool Windows | Database). This data source should point to the same DB that your entities use.
  2. Add “JavaEE Persistence” framework support to test-jpa (right click module | Add framework support…). Click OK
  3. Open the Persistence Window (View | Tool Windows | Persistence)
  4. In this window, you will assign a data source to test-jpa (right click module | Assign data sources)
  5. In the Assign Data Sources window, you will see a line with the value “Entities” which points to an empty Data Source field. Click on this field and select the data source from step 1. Click OK.
  6. In the Persistence Window, expand the module and right click on Entities | Console. You have a choice between JPA and Hibernate Console.

Some cool features that both Consoles support:

  • Navigating to the declaration of a class or field
  • Auto-completion
  • Parameterized queries

Reference: https://www.jetbrains.com/help/idea/using-jpa-console.html

One last thing: I’m new at writing posts. If you have any suggestions to make this post more clear, please write a comment.

Inspecting in-mem HSQLDB

Sometimes, for automatic testing of your Java application, you need to configure a DB connection. Most of the times the decision is to go for an in-memory database and HSQLDB is a prime candidate.

And some other times your tests will be failing and it would be great to see the DB status before the failure. I already knew of the option of running HSQLDB as a server, but a colleague showed me a simpler way, with less configuration.

Simply add the following lines to the beginning or the test:

System.setProperty(“java.awt.headless”, “false”); // to prevent an exception related to awt running headless
DatabaseManagerSwing.main(new String[]{“--url”, “jdbc:hsqldb:mem:testdb”, “--user”, “sa”, “--password”, “”}); //to launch a separate a simple DB-inspector window

Normally, you’re going to put a breakpoint in your test right before the failing assertions. If the DB-inspector window freezes it’s because the breakpoint is configured to stop all threads. You will need to configure your IDE to not stop the DB-inspector thread (on IntelliJ IDEA, right click on the breakpoint and you’ll get the menu that allows you to change this).

References:

One last thing: I’m new at writing posts. If you have any suggestions to make this post more clear, please write a comment.

Excluding Hibernate entities from auto-generation

Today I had to do something completely new with Hibernate, within the scope of a unit test. I had a group of entities and wanted to exclude one of them from the schema auto-generation (hibernate.hbm2ddl.auto=create).

After spending a couple of hours trying out different things and reading Stackoverflow answers, I hit jackpot with this cool solution:

  • implement the SchemaFilterProvider and the SchemaFilter interfaces
  • in the SchemaFilter implementation, add an if condition to includeTable so that it returns false for the table that you don’t want to create
  • add hibernate.properties to the classpath and define hibernate.hbm2ddl.schema_filter_provider to point to the SchemaFilterProvider implementation

What follows is an example of an implementation. In my case, I want to exclude all entities that would create a table that has namespace in its name.

https://gist.github.com/treaz/4c576f6701385a727a6df4cd479089d5https://gist.github.com/treaz/3cd4ec457eefbf2b79ce01a527022160

Reference: https://stackoverflow.com/questions/6212144/how-to-disable-schema-validation-in-hibernate-for-certain-entities

One last thing: I’m new at writing posts. If you have any suggestions to make this post more clear, please write a comment.