Sunday, 13 May 2012

Testing getters and setters with openpojo

Testing getters and setters is a little bit controversial topic. However, if we decide to do it or if we are forced to, we can ease the task with openpojo library.

Generally standard getters and setters can be generated by your IDE but testing them is a manual work - it takes some time and seems to be boring. So if the code was generated, why can't we automate the testing?
openpojo doesn't generate the unit test but it allows to test your POJO with a very small effort.

Let's take a look at an example. We have a Person class which is a POJO with generated getters and setters.

To test it we need to create just one class:

Our class defines which rules openpojo will apply and what tests it will execute. We also specify which package will be tested - if we have a lot of classes we can test them all in one go. In our case we're only testing if  getters and setters exist and if they behaving in a conventional way.
Running the class with any coverage tool will show us that the get and set methods are executed.
There are more rules that we can apply (like checking if there are no public fields, no primitive values etc.). We can write our own rules as well.

No comments:

Post a Comment