Unit Testing – a quick start guide to JUnit

JUnit is the de facto standard framework for writing Java unit tests. As scala is a language that creates Java classes you can also write JUnit tests for scala classes, either in scala or Java itself.

A quick way to get started would be to download eclipse for Java developers from here (you will need Java installed).

Once downloaded, open eclipse and create a new Java Project called Test, accepting the defaults.

Expand the Test project and right-click on the src folder, choosing New and then JUnit Test Case. You may need to filter the options to find JUnit and JUnit Test Case.

In the next dialog enter TestString for the Name and com.test for the package. You should be prompted whether to add JUnit to the project build path, choose Yes.

Depending on any options for code generation, you should now have a new class that looks roughly like this:

package com.test;

import static org.junit.Assert.*;
import org.junit.Test;

public class StringTest {

	@Test
	public void test() {
		fail("Not yet implemented");
	}
}

When we run this class JUnit will automatically invoke the test() method because it has a @Test annotation. Let’s try it – right-click the StringTest class and choose Run As -> JUnit Test.

The failure in the JUnit panel should contain a failure trace that looks something like this:

java.lang.AssertionError: Not yet implemented
	at com.test.StringTest.test(StringTest.java:11)

This is because we have a line in out test saying ‘fail’. If we just remove this we will have an empty test that passes, but where’s the fun in that. Let’s make an assertion instead. Replace the method contents to look like this:

@Test
public void test() {
  String name = "Vinny";
  assertEquals(5, name.length());
}

Now when we run it there is no failure trace, because the length (number of characters) of the String “Vinny” is 5. Change the number from 5 to a different integer value and the test will fail. This is our first JUnit test, we didn’t create our own class to test but did test something, namely the ‘length()’ method of the String class.

By convention we would have a test class in a folder called src/test/java. Typically we would have the package of our Test class (what we call a TestCase) in the same package as the class being tested.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s