Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

JUnit Tips

A Whirlwind Introduction to JUnit

Writing your own software tests in Java is   simple and clean. This guide will show you how to simplify some of the less common tasks as well.


Background info:

What is Test-Driven Development?

What is JUnit?

A Supplemental Library Just do it

For student use, we provide a supplemental library (already available to all assignments on Web-CAT) that enhances basic JUnit features in a number of ways that will make your life easier. There are two steps to using this support: make sure the appropriate jar files are on your classpath, and then use a specific base class for all your test cases (even if you are using JUnit 4 techniques--use the provided base class anyway).

To set up your classpath, download the following jar file:

student.jar

Place this jar on your project build path. If you're using Eclipse and you've already added Eclipse's built-in JUnit library to your project, ensure that student.jar comes before Eclipse's JUnit library in the search order--or just remove Eclipse's JUnit library from the build path entirely.

All the test classes you create should then extend the base class student.TestCase . This class is itself a custom subclass of junit.framework.TestCase , so all normal JUnit practices still work. The advantages of using this subclass include:

Built-in methods to provide stdin content to code being tested, as well as to check stdout content produced.

Better messages for some assertions, and better error checking for others.

Ability to use JUnit 4 annotations and programming style, if you prefer that over JUnit 3.

Protections for System.exit() calls in code under test (i.e., if your code calls System.exit() , this raises an exception in your test case that you can catch, rather than terminating the virtual machine).

Extra assertions that support "fuzzy" string matching (ignoring punctionation, capitalization, spacing, etc.).

A specialized subclass, GUITestCase , provides full support for testing Swing applications with graphical interfaces.

Platform-independent line ending normalization for text, so that tests do not need to include platform-specific line terminators.

Simple methods to load text from a file (for use as either input or expected output), or for writing slightly cleaner multi-line text literals in your code.

For full details, see the Javadoc documentation for student.TestCase .

Creating a JUnit Test Case based on version 3.x (without annotations)

1. import

Import the JUnit classes so you can use them in your code.

1 import student.TestCase;

2 ...

2. create your class

Your class should be named using the JUnit convention with the name of the class you are testing followed by the word Test.

If you class is named Student , then your test will be named StudentTest .

1 import student.TestCase;

2

3 public class StudentTest

4 extends TestCase

5 {

6 // code goes here...

7 }

3. define your test cases

Test cases are defined using methods with names that start with test...() .

Typically, your method will be named following the method you are testing in your source code. The example to the right tests the setName() method, so it is called testSetName() . For more complicated methods, you may have many tests (e.g., testFoo1() , testFoo2() , testFoo3() , etc.).

You have to test your assumptions/expectations of your code using an assertXXX() method call. These are provided by the TestCase base class.

1 import student.TestCase;


2

3 public class StudentTest

4 extends TestCase

5 {

6 private Student aStudent;

7

8 public void setUp()

9 {

10 // fixture to be used for testing

11 aStudent = new Student("Joe", "888-2993");

12 }

13

14 public void testSetName()

15 {

16 aStudent.setName("Manuel");

17 assertEquals(aStudent.getName(), "Manuel");

18 }

19 }


Available Assert Methods

The most common assert...() methods you will use to express the expected outcomes in a test case are:

Method                      Meaning

assertEquals(x, y);    Assert that two values are equal, using the equals(Object) method to compare them. This is the most commonly used assert method in your arsenal.

assertEquals(x, y, delta);    Assert that two floating point values are equal, within some tolerance delta. Because of the inexactness of floating point representations, it is incorrect to test that two floating point values are equal using numeric equality (==). Fortunately, if you try this while using student.TestCase , you'll get an appropriate diagnostic error. Instead, always specify a tolerance value: how close to the expected value does the computed number have to be?

assertTrue(condition);    Assert that a boolean condition is true.

assertFalse(condition);    Assert that a boolean condition is false.

assertNull(x);    Assert that a reference is null.

assertNotNull(x);    Assert that a reference is not null.

assertSame(x, y);    Assert that two references refer to the same destination (i.e., two variables refer to the same object). This is the same as performing an == equality comparison between reference variables.

There are many more assert methods than those listed here, but these are by far the most common.

Using Fixtures in JUnit Testing

1. import and create your test class

Import the JUnit classes so you can use them in your code.


1 import student.TestCase;

3 public class StudentTest

4 extends TestCase

5 {

6 // code goes here...

7 }


2. define your fixtures

Fixtures are objects that are used in your test cases.

Define your fixtures as private fields in your test class (instance variables).

Initialize your fixture in the setUp() method.

The setUp() method is called automatically before each test method is executed, to ensure each test operates on a clean set of freshly initialized objects.


1 import student.TestCase;

3 public class StudentTest

4 extends TestCase

5 {

6 private Student aStudent; // fixture to be used for testing

8 public void setUp()

9 {

10 // initialize it here

11 aStudent = new Student("Joe", "888-2993");

12 }

13 }


3. use fixtures in your test cases

The two test cases on the right run succesfully, since they each start with a freshly generated copy of the aStudent object.

1 ...


2 public void testSetName()

3 {

4 assertEquals(aStudent.getName(), "Joe");

6 aStudent.setName("Manuel");

7 assertEquals(aStudent.getName(), "Manuel");

8 }

10 public void testSomethingElse()

11 {

12 // aStudent .. is new here

13 assertEquals(aStudent.getName(), "Joe");

14 assertEquals(aStudent.getID(), "888-2993");

15 }

16 }