You are here

Using JUnit in DrJava

26 July, 2019 - 09:51
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6

Suppose we have a class such as the following that we wish to test. Note that class is public and that the method we wish to test is also public.

Sample Code To Be Tested

media/image1.png
Figure 7.1
Some example code to be tested. 

In DrJava, select "File/New JUnit Test Case...". Enter a name that is descriptive of the test(s) you wish to make. A recommendation is to use the class name being tested prepended with "Test_", such as "Test_MyClass". This enables all your test classes to be easily identified, DrJava will then automatically create a valid JUnit test class, such as below.

Note: DrJava does not initially name the new class file, but the default name suggested by DrJava when you attempt to save it will be correct.

Autogenerated Unit Test Class

media/image2.png
Figure 7.2 Test class autogenerated by DrJava. 

Rename the auto-generated "testX()" method to something more descriptive of the particular test you'd like to perform. The new name must start with "test" and must return void and take no input parameters. You can create as many test methods as you wish to test your code. JUnit will automatically run all methods that begin with "test" as test methods. Typically, a single test method will test a single method on the class under test. There are situations however where a single method under test may require several test methods to properly test its full range of operation. In the code that follows, the testX() method has been renamed to "test myMethod1()".