martes, junio 26, 2012

Bye, Bye, 5 * 60 * 1000 //Five Minutes, Bye, Bye

Llueve, llueve, y mientras nos mojamos como tontos. LLueve, llueve, y en un simple charco a veces nos ahogamos. (Llueve - Melendi)

In this post I am going to talk about one class that was first introduced in version 1.5, that I have used too much but talking with some people they said that they didn't know it exists. This class is TimeUnit.

TimeUnit class represents time durations at a given unit of granularity and also provides utility methods to convert to different units, and methods to perform timing delays.

TimeUnit is an enum with seven levels of granularity: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS and SECONDS.

The first feature that I find useful is the convert method. With this method you can say good bye to typical:

     private static final int FIVE_SECONDS_IN_MILLIS = 1000 * 5;

to something like:

     long duration = TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS);

But also equivalent operations in a better readable method exist. For example the same conversion could be expressed as:

     long duration = TimeUnit.SECONDS.toMillis(5);

The second really useful sets of operations are those related with stopping current thread.

For example you can sleep current thread with method:


instead of:


But you can also use it with join and wait with timeout.

     Thread t = new Thread();
     TimeUnit.SECONDS.timedJoin(t, 5);

So as we can see TimeUnit class is though in terms of expressiveness, you can do the same as you do previously but in a more fashionable way. Notice that you can also use static import and code will be even more readable.

Keep Learning,

martes, junio 19, 2012

NoSQLUnit 0.3.0 Released

Se você me olhar vou querer te pegar, E depois namorar curtição, Que hoje vai rolar... (Balada Boa - Gustavo Lima)


Unit testing is a method by which the smallest testable part of an application is validated. Unit tests must follow the FIRST Rules; these are Fast, Isolated, Repeatable, Self-Validated and Timely.

It is strange to think about a JEE application without persistence layer (typical Relational databases or new NoSQL databases) so should be interesting to write unit tests of persistence layer too. When we are writing unit tests of persistence layer we should focus on to not break two main concepts of FIRST rules, the fast and the isolated ones.

Our tests will be fast if they don't access network nor filesystem, and in case of persistence systems network and filesystem are the most used resources. In case of RDBMS ( SQL ), many Java in-memory databases exist like Apache Derby , H2 or HSQLDB . These databases, as their name suggests are embedded into your program and data are stored in memory, so your tests are still fast. The problem is with NoSQL systems, because of their heterogeneity. Some systems work using Document approach (like MongoDb ), other ones Column (like Hbase ), or Graph (like Neo4J ). For this reason the in-memory mode should be provided by the vendor, there is no a generic solution.

Our tests must be isolated from themselves. It is not acceptable that one test method modifies the result of another test method. In case of persistence tests this scenario occurs when previous test method insert an entry to database and next test method execution finds the change. So before execution of each test, database should be found in a known state. Note that if your test found database in a known state, test will be repeatable, if test assertion depends on previous test execution, each execution will be unique. For homogeneous systems like RDBMS , DBUnit exists to maintain database in a known state before each execution. But there is no like DBUnit framework for heterogeneous NoSQL systems.

NoSQLUnit resolves this problem by providing a JUnit extension which helps us to manage lifecycle of NoSQL systems and also take care of maintaining databases into known state.


NoSQLUnit is a JUnit extension to make writing unit and integration tests of systems that use NoSQL backend easier and is composed by two sets of Rules and a group of annotations.

First set of Rules are those responsible of managing database lifecycle; there are two for each supported backend.

  • The first one (in case it is possible) it is the in-memory mode. This mode takes care of starting and stopping database system in "in-memory" mode. This mode will be typically used during unit testing execution.

  • The second one is the managed mode. This mode is in charge of starting NoSQL server but as remote process (in local machine) and stopping it. This will typically used during integration testing execution.

Second set of Rules are those responsible of maintaining database into known state. Each supported backend will have its own, and can be understood as a connection to defined database which will be used to execute the required operations for maintaining the stability of the system.

Note that because NoSQL databases are heterogeneous, each system will require its own implementation.

And finally two annotations are provided, @UsingDataSet and @ShouldMatchDataSet , (thank you so much Arquillian people for the name) to specify locations of datasets and expected datasets.

MongoDb Example

Now I am going to explain a very simple example of how to use NoSQLUnit, for full explanation of all features provided, please read documentation in link or download in pdf format.

To use NoSQLUnit with MongoDb you only need to add next dependency:

First step is defining which lifecycle management strategy is required for your tests. Depending on kind of test you are implementing (unit test, integration test, deployment test, ...) you will require an in-memory approach, managed approach or remote approach.

For this example we are going to use managed approach using ManagedMongoDb Rule) but note that in-memory MongoDb management is also supported (see documentation how).

Next step is configuring Mongodb rule in charge of maintaining MongoDb database into known state by inserting and deleting defined datasets. You must register MongoDbRule JUnit rule class, which requires a configuration parameter with information like host, port or database name.

To make developer's life easier and code more readable, a fluent interface can be used to create these configuration objects.

Let's see the code:

First thing is a simple POJO class that will be used as model class:

Next business class is the responsible of managing access to MongoDb server:

And now it is time for testing. In next test we are going to validate that a book is inserted correctly into database.

See that first of all we are creating using ClassRule annotation a managed connection to MongoDb server. In this case we are configuring MongoDb path programmatically, but also can be set from MONGO_HOME environment variable. See here full description of all available parameters.

This Rule will be executed when test is loaded and will start a MongoDb instance. Also will shutdown the server when all tests have been executed.

Next Rule is executed before any test method, and is responsible of maintaining database into known state. Note that we are only configuring working database, in this case the test one.

And finally we annotate method test with @UsingDataSet indicating where to find data to be inserted before execution of each test, and @ShouldMatchDataSet locating expected dataset.

We are setting an initial dataset in file initialData.json located at classpath com/lordofthejars/nosqlunit/demo/mongodb/initialData.json and expected dataset called expectedData.json.

Final Notes

Although NoSQLUnit is at early stages, the part of MongoDb is almost finished, in next releases new features and of course new databases will be supported. Next NoSQL supported engines will be Neo4J, Cassandra, HBase and CouchDb.

Also read the documentation where you will find an full explanation of each feature explained here.

And finally any suggestion you have, any recommendation, or any advice will be welcomed.

Stay In Touch

Email: asotobu at

Blog: Lord Of The Jars
Twitter: @alexsotob
Github: NoSQLUnit Github

Keep Learning,

Full Code

viernes, junio 08, 2012

Testing Abstract Classes (and Template Method Pattern in Particular)

Sick at heart and lonely, deep in dark despair. Thinking one thought only, where is she tell me where. (Heart Full of Soul - The Yardbirds).

From wikipedia "A template method defines the program skeleton of an algorithm. One or more of the algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed".

Typically this pattern is composed by two or more classes, one that is an abstract class providing template methods (non-abstract) that have calls to abstract methods implemented by one or more concrete subclasses.

Often template abstract class and concrete implementations reside in the same project, but depending on the scope of the project, these concrete objects will be implemented into another project.

In this post we are going to see how to test template method pattern when concrete classes are implemented on external project, or more general how to test abstract classes.

Let's see a simple example of template method pattern. Consider a class which is responsible of receiving a vector of integers and calculate the Euclidean norm. These integers could be received from multiple sources, and is left to each project to provide a way to obtain them.

The template class looks like:

Now another project could extend previous class and make an implementation of  abstract calculator by providing an implementation of read() method .

Developer that has written a concrete implementation will test only read() method, he can "trust" that developer of abstract class has tested non-abstract methods.

But how are we going to write unit tests over calculate method if class is abstract and an implementation of read() method is required?

The first approach could be creating a fake implementation:

This is not a bad approach, but has some disadvantages:
  • Test will be less readable, readers should know the existence of these fake classes and must know exactly what are they doing. 
  • As a test writer you will spend time in implementing fake classes, in this case it is simple, but your project could have more than one abstract class without implementation, or even with more than one abstract method.
  • Behaviour of fake classes are "hard-coded".
A better way is using Mockito to mock only abstract method meanwhile implementation of non-abstract methods are called.

Mockito simplifies the testing of abstract classes by calling real methods, and only stubbing abstract methods. See that in this case because we are calling real methods by default, instead of using the typical when() then() structure, doReturn schema must be used.

Of course this approach can be only used if your project does not contain a concrete implementation of algorithm or your project will be a part of a 3rd party library on another project. In the other cases the best way of attacking the problem is by testing the implemented class.

Download sourcecode


Donate If You Can and Find Post Useful