JUnit, unit test for Java

In one of the previous posts about Ant we mentioned that Ant supports JUnit unit test.

Now let’s talk about JUnit itself. Basic tutorial is available at the source, so we will go a little bit deeper.

As we were saying in out Java tutorial we seldom have projects where everything is kept in one folder.

To create more or less real life example let’s follow my sample which I created for this post. You can get it here.

One you get the code let’s take a look inside. You will find two folders: src with all source code and lib with third-party libraries (JUnit in our case).
Now run

ant clean-build

and again let’s look inside. You will find two more folders: classes with output code and out with jar file.
That’s the organization which would satisfy most projects.

Now let’s clean it up and start from the beginning. Run

ant clean

we are back to source code and libs.

Take a look at the source code first. We are expanding our previous Java tutorial.
Our main class is HelloWorld.java only this time we have some additional classes in utils folder and HelloWorld is printing line which it gets from StrUtils getGreeting static function (see StrUtils.java file and HelloWorld.java for details).
Let’s build it manually:
1. create folder classes: mkdir classes
2. compile: javac -sourcepath src -d classes src/ak/*.java
3. run: java -cp classes/ ak.HelloWorld
You should see “Hello, World”

Isn’t it supposed to be about unit test? Oh, yes! Go back to the source code. As you remember our output string is coming from utility class, let’s create a unit test for it. Well, it’s already created – take a look at src/tests folder – there you will find three test files, each for corresponding main class.

Let’s build it manually:
1. compile: javac -cp lib/junit-4.12.jar:lib/hamcrest-core-1.3.jar -sourcepath src -d classes src/**/*.java
2. run: java -cp classes:lib/junit-4.12.jar:lib/hamcrest-core-1.3.jar org.junit.runner.JUnitCore tests.StrUtilsTest
You should see “…OK (1 Test)”

Let’s run test which would fail:
3. run: java -cp classes:lib/junit-4.12.jar:lib/hamcrest-core-1.3.jar org.junit.runner.JUnitCore tests.UtilsTest
This file you should see “…FAILURES!!! Test run: 2, Failures: 1”

Usually you won’t be running one test at a time, but sometimes it’s useful to do while you working on some specific feature.
To run all tests best way is to use Ant:

ant clean-build
ant junit
ant junitreport

“ant junit” would give you result right away, but more readable format you can get by running “ant junitreport”.

After it’s done go to unit_report folder and open index.html, you should see report with three tests run with two succeeded and one failure.

Leave a Reply