Sunday 25 August 2013

Simple JUnit Example Test

This is a simple introduction to using JUnit to unit test classes.

I am writing this post because recently a friend of mine started to dabble in Java and in order to test his code he was fiddling around with a main method and printing expected output etc.  Manual tests like this can seem quick initially, but you can't check everything every time you make a change. Investing half an hour in setting up some tests will save you oodles of time later.

Put JUnit on your classpath

You can manually add it by downloading it from the junit site and in your eclipse project do the following: 

Right click on JRE System Library > Build Path > Configure Build Path > Libraries > Add External Jar. 

Navigate to wherever you have stored the junit jar locally and click okay: it should now be on your classpath (and you should see junit.jar or something similar under 'JRE System Library').

Alternatively you can use a nice dependency management tool like Maven or Ivy.  With Maven you don't even need to do anything - JUnit jars are on the classpath by default when you create a maven project. 

Sample class to Test

 I have a very simple 'Circle.java' class with 1 method to test: 



Using JUnit to write tests

Test methods have the annotation '@Test' above them.  The '@Before' annotation means that that method (in this case the method called 'setup') is called before every class. 

Note that all test methods (ie methods with the @Test annotation must be public, void, and take in no parameters). 


To run this test from eclipse - 
Right click anywhere in the class > Run As > JUnit Test

Boom, done. 







No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...