Junits – Introduction

I am no expert at JUnits. The fact is, until 2 months from now, I was dead scared from this word. I even told my new project architect that Junits is something that gives me heebie-jeebies. But he assured me and told me that it is a very easy task.

For those of us who do not know, Junit is a java code which is used to test the logic of our workable code. It is mainly used for black box testing, which means using some input, your workable code is expected to give some expected output. It thus helps in identifying and testing boundary cases as well.

Uptil now, I am never able to write them . But, the saying  that practice makes a man perfect has been accepted as a universal saying for some good reason.And the reason is, that it is hell of a correct saying. Practice, and a few ground rules can make your life simple at any task.

My ground rule of writing junit is :

  1. “Write only the amount which can make the code pass”

And following this, I always take the step of creating the basic structure of Junit, like writing injectMock, writing !before function, writing @test empty function and testing it. This will prove whether your test is runnable or now, or whether or not you are getting those creepy errors of “ClassNotFoundException”. Next, you will put your code in debug mode and will see where your code breaks according to your test. That is the point you will have to add something mock or some given to make sure that that line passes smoothly. This way, you will never write extra in your junit. And within no time, you can write some of the most complex junit as well.

2) “There is no such thing as mocking static methods”

Junits do not allow testing private methods since they are not visible and static methods since they cannot be mocked. On googling how to mock static methods, you will get solutions like using power mockito, but that will cost you adding whole new set of libraries to make powermockito running.Static methods are normally called in your code through class name directly. Try bringing the static method call during debug, most of the time you will see that that line will just pass through leaving you doing nothing.

That’s pretty much the basic rules. I plan to write more, may be a couple of columns giving details and tricks to write junits. Most importantly, one column will be on how to make junits run through eclipse efficiently .




Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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