The road so far….

April 7, 2013

Junit Recepies : Having common Setup and Teardown

Filed under: Agile, java — Tags: , — Rahul Sharma @ 7:56 pm

The other day I was refactoring one of our apis. We were removing some of the columns as they were not required. I believe in this exercise dropping the column was the most easy part. After that I removed the corresponding fields from the associated ORM and it was fine for the business related code.  But !! the big one, was my code was not compilable, as the object was being used in a lot of tests and thus my project was all painted RED.

While I was fixing all the required tests I realized most of the tests were on similar lines. We were pushing some data in tests, creating some required resources and then destroying them after the tests were done. Now we have blatantly copied the stuff in every testcase  with total disregard to the DRY principle.

Fixing this meant fixing every test case. But that was not the solution as tomorrow if we changed some thing else then we will be required to do this in very test case. One possible fix for the issue at hand meant making a static class and then making calls from the @before and @after methods in every test. This again will not fulfil the wishes as we need to call @before and @after in every test case  😦

One of the better ways of removing such a duplication is by using Junit @Rule. Most of us has used TemporaryPath Junit rule, so on similar concept we created ApplicationStartRule by extending the ExternalResource interface. It provides the before and after method which could be implemented to include all the custom processing required.

class ApplicationStartRule extends ExternalResource {
 UserRepositry userRepositry;
 private UserData userdata;

 protected void after() {

 protected void before() throws Throwable {

You can build custom rules in this way and include the only required one in your test case. This is a great way of improving  your test cases.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: