JUnit and Mockito handbook

One of the most important concepts to build a software with quality is the automated tests. Going deep into the automated tests, one of its most explored branches is the unit tests. This article will show an overview about unit tests and then a practical “JUnit and Mockito handbook”, presenting their most useful features and some usage examples.

What is a unit test?

A unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested. The percentage of code which is tested by unit tests is typically called test coverage.

A unit test targets a small unit of code, generally a method from a class.

Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you need to modify code for fixing a bug or extending functionality. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

What are the values of unit tests?

  • Confidence

One of the most valuable benefits of unit tests is that they give you confidence that your code works as you expect it to work. Unit tests give you the confidence to do long-term development because with unit tests in place, you know that your foundation code is dependable. Unit tests give you the confidence to refactor your code to make it cleaner and more efficient.

  • Time

Unit tests also save you time because unit tests help prevent regressions from being introduced and released. Once a bug is found, you can write a unit test for it, you can fix the bug, and the bug can never make it to production again because the unit tests will catch it in the future.

  • Documentation

Another advantage is that unit tests provide excellent implicit documentation because they show exactly how the code is designed to be used.

Persisting enums using JPA attribute converter

Before the JPA 2.1 specification be released in 2013 the simple task to persist and load enums could be performed but not in a simple and decent way. In this article I’m going to present you some old techniques to solve this problem and how the new JPA specification established an appropriate way for persisting enums using JPA attribute converter.

To access the complete JSR 338: Java Persistent 2.1 specification, please follow this link: https://jcp.org/en/jsr/detail?id=338.

Back in the old days (before the JPA 2.1)

The Enumerated techinique

One of the most spreaded solutions for the enums’ persistence problem was the Enumerated technique. It consists in the usage of the Enumerated annotation with EnumType.ORDINAL or EnumType.STRING. I personally don’t like this approach because when we use the EnumType.ORDINAL it assumes the position of the items will never change inside the enum and when using EnumType.STRING we will persist the same string repeated times in the DB.

Java 8 Lambda expressions and exceptions

Java 8 has introduced a lot of new features, many of them well known by other languages, like lambdas expressions. Lambdas are really useful when you are encapsulating a single unit of behavior that you want to pass to other code. For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error. So… whats the problem with Java 8 lambda expressions and exceptions?

By default, Java 8 provides some predefined functional interfaces that can be implemented and used as a lambda expression. You can find these implementations within the package “java.util.function”. Some examples of these functional interfaces are: Consumer, Predicate, Supplier and so on. For more information about them, check this page.
One point that is important to notice when observing these predefined interfaces is that none of them define a method that throws exceptions.

Mocking the current date-time (properly) with Java

It’s not unusual to face situations where we need to capture the current system’s date-time in order to calculate some future date, make validations and so on. The problem generally appears as soon as we need to check whether some calculated date was correctly generated or not. When we directly use the instruction “new Date()” to retrieve the current system’s date-time it’s hard to mock it afterwards. I’ve seen people using many approaches to get the mocked current date-time and it’s possible to assure that the majority of them is not elegant neither simple.

You can look at some approaches here:
http://stackoverflow.com/questions/11887799/how-to-mock-new-date-in-java-using-mockito

Now I will present you a simple code example that uses the “new Date()” and it’s definitely NOT easy to test.

Salvando o resultado de consultas MySQL em arquivos CSV

Uma característica meio desconhecida do MySQL, também presente em outros bancos de dados como o Oracle, é a de exportar o resultado de consultas diretamente para arquivos. Esta particularidade do MySQL é bem interessante quando precisamos fazer alguma exportação pontual de dados, que posteriormente possam ser importados em ferramentas como o Excel.

Mas vamos ao que interessa, para exportamos o resultset de uma consulta vamos utilizar as instruções “INTO OUTFILE”, “FIELDS TERMINATED BY”, “ENCLOSED BY” e “LINES TERMINATED BY”.

Segue abaixo um exemplo de como usar as instruções: