2016. december 19., hétfő

Using logging in your unit test

When running unit test, you are not supposed to be checking the logs, generated by the test framework. One of the first principles of the test driving development paradigm is, that you should be able to run your tests automatically, without any developer interaction. You also should not be forced to check any output besides the running result. Also you should never check the log, to be able to decide if running the test was successful.

So long the theory.

In fact, sometimes it is very helpful, if you can analyse logging from your unit test. As you are working test driven, you use the unit test runner also for developing the code. In order to get a closer view to the process you are implementing, during the development phase, it can spare a lots of time and debugging, if you can have a look at the logs.

The problem is, that you do not want the change the log level in your code, to let JUnit process to log your debug or trace level logs. As JUnit is running with default INFO level (depending on the actual logging implementation you are using), you need to find a way to change the logging level fast.

Change the logging level in Eclipse

You can define a custom log configuration file for your JUnit runner

-Djava.util.logging.config.file=scr/test/resources/logging.properties












To define a custom log settings file, you need to open the actual run configuration, and add the path of the file as program argument.

Although this method is handy to use, when you have a central run configuration, and you want to run it several time during your development, in most cases it is inconvenient. You need to define the same run-time argument for all run or debug configuration, which makes the development slow.

Set log level programmatically    

Thanks to the API of logging frameworks, it is possible to set the log level dynamically in your code. The @Before method is just a right place for it. Unfortunately you need to remember slightly different API calls for different logging frameworks, but if you stick to one, it is not a huge problem.

Here you can see implementation for Log4J and Slf4j, the two most used by me.



As you can see, once you got a reference to the root logger, you are free to change any settings the given API allows to you.

Please consider, that logging on such a wide scale is usually unnecessary after the development phase. I usually use this possibility only when creating new features, and remove it or comment it out after the code works as desired.



Custom toString builder for Eclipse




If you are not satisfied the way, how Eclipse generates the toString method for your classes, and you are not so lucky to use the Lombok project, you have the possibility to set custom toString builder for Eclipse.

In the Generate toString dialog you can configure the code style.





By clicking on the Configure button, you can open the Configure Custom toString Builder dialog.




Here you can define the class used for generating the toString method. In the above example I use the ToStringBuilder from Apache Commons (org.apache.commons.lang.builder.ToStringBuilder), but you can implement your own builder class, that meets the requirements.

The generated method looks like this:

    @Override
    public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this);
        builder.append("period", period).append("orderPosition", orderPosition).append("selectable", selectable).append("name_e", name_e);
        return builder.toString();
    }


As I wanted to generate toString in XML and JSON format, I have implemented my own tostring builder classes.

My builders have the advantage, that they do not use reflection, to generate the String representation of the classes. The disadvantage is, that they work only with relative simple classes. But as I try to keep my classes clean and simple, it is not a real problem for my projects.

It is relative easy to implement a class, which satisfies the requirement of a custom Eclipse ToString() Builder. Here is an example, how I created a JSON-like toString() builder class:



Please note, that in order for Eclipse to use the fluent API, for calling the append() method, I needed to implement the Builder Interface.

The configuration of the class to be used as a builder looks like this:




The generated method looks like this:









2016. december 6., kedd

Use standard Java APIs instead of reimplementing it


While we are joyfully solving our tasks, we tend to forget, how much help we can get form standard Java API. Before implementing something very exciting, elegant and nice, it is always a useful tactic to stop ourselves, take a big breath, and check if the function is already available somewhere.

While making code reviews for my colleagues, I keep finding methods and functions, that are long time in Java, or in some commonly used utility library. It is embarrassing, while using the existing solution you could have spare the time for recreating, testing and maintaining your custom solution.

I believe, that knowing the basic Java functionality tells a lot about the programmer, and the way of coding, he works in the daily life.

Advantages of using standard Java API:

  • hundred percent tested
  • stable, long term available code 
  • in most cases, the existing solution is a way more elegant and effective implementation, than the one you come up with

So my advice is, try to find the function, you need, first in the default Java API, then in a commonly used library. Implement your solution, only if you are really sure, that it has not been done yet.

Sources to be checked:



Here are some examples of using Java API, instead of reimplement them:

Null-safe compare

Comparing two objects, considering that they both can be null, is a tricky one. I have seen some elegant and some less elegant implementation of it. But the best one, I saw is in the Objects class of Java ;)

Null-safe toString

If you use code like this

return delta == null ? "" : delta.toString()

you should consider using Objects.toString() instead. It provides a null-safe conversion, and avoids returning Strings, containing "null".

Do not create empty collections

Use built in constants in java.util.Collections

  • EMPTY_SET
  • EMPTY_LIST
  • EMPTY_MAP

Use already existing exceptions

A huge amount of predefined exceptions exists already in default Java packages. Why to implement your own exceptions, when we have so many, like:
  • java.lang.IllegalStateException
  • java.lang.IllegalArgumentException
  • java.util.MissingResourceException
  • java.util.IllegalFormatException

Array operations

Programmers tend to implement operations on arrays, only because ArrayUtils form commons does not contain the required function. They forget, that some of them is not implemented on purpose, while Arrays form java.util already contains them. Most useful ones, for my point of view are:

  • copyOf
  • fill
  • toString
  • deepEquals

Using builder for toString

Not everyone is so lucky, to be allowed to use the Lombok project for dynamic code generation, via annotations. Without a proper framework developers tend to let the IDE generate the toString method for classes. The problem is with the maintainability. Namely, it is often forgotten to regenerate the method, if the class changes.

The solution is the ToStringBuilder form Apache Commons. You have the possibility to generate toString via reflection.

At the end of your development phase, when it is probably, that your code will seldom be changed, you can generate a toString, without reflection. For this purpose, you can configure Eclipse to use ToStringBuilder instead of the built-in generator.