The aims of these exercises are to:
Familiarise yourself with the JUnit package for testing Java code.
Experience running and writing JUnit tests in the Eclipse IDE.
Refresh your memory of Java reference types by completing a couple of programming exercises.
Students should read Weiss Chapter 2 in preparation for these lab exercises.
Programming Exercise (Weiss 2.14)
Implement the following methods, that accept an array of double and
return the sum, average, mode (most common item) in the array, and standard deviation of the values.
public static double sum( double [ ] arr )
public static double average( double [ ] arr )
public static double mode( double [ ] arr )
public static double stddev( double [ ] arr )
Take the tutorial on
Writing and running JUnit tests in the Eclipse tutorial:
Java development user guide > Getting Started > Basic tutorial
.
Then copy the provided JUnit test class
lab02Test.java
into your project workspace.
Run the JUnit test cases of lab02Test.java
to test the code you have just written.
The JUnit test cases will almost certainly show you some cases you have not considered.
Such errors are called bugs. They are very common in programming, and experienced programmers
make (and fix!) them all the time.
Using JUnit tests helps developers to find the bugs more quickly,
and so to write better quality code, and to be more productive.
Bugs are shown in JUnit as a failed test case, with a red bar. Study the error message given, correct your code,
and continue. Your aim is for your code to pass all test cases: in which case you will see a green bar, signalling success.
Programming Exercise 2 (Weiss 2.17)
Implement the following methods that return the minimum of the group
of items passed as the parameter. In the case of Strings, the minimum is
the alphabetically smallest, as determined by compareTo
.
public static int min( int [ ] arr )
public static int min( int [ ][ ] arr )
public static String min( String [ ] arr )
public static String min( ArrayList
Create some JUnit tests for your new class. Write some examples including normal, exceptional and boundary cases for each method. Your tests need not cover all functionality, but you should write enough tests to get familiar with the system. Use the JUnit test class from the previous question as a model for your test code.
Programming Exercise (Weiss 2.24) Implement a method
public static ArrayList
Your method should return an ArrayList containing
all the Strings in arr
that begin with character ch
.
Write some JUnit test cases for your method. Run some test cases written by other students. In professional practice test cases are usually written by an independent team rather than the developers.