4. Unit Tests
Feel free to use your laptop
You are strongly encourage to work with others
When you get stuck, ask those sitting around you for help
Get used to working together in the labs
Peer teaching and peer learning has been empirically shown to be very effective
4.1. Before Unit Testing
This lab focuses on writing unit tests for the Course
and CourseList
classes described in the
Objects Lab and
Collections Lab respectively. These classes are to be completed before
writing the unit tests. If these classes are not complete, complete them before continuing.
4.2. Unit Testing
It is always important to ensure code correctness. For this reason, unit tests are written as they help programmers test their code to demonstrate correctness in a systematic way. While working on this lab, it is strongly recommended to refer to the relevant topic on unit testing.
4.2.1. Testing the Course
Class
Note
Give the test methods descriptive names while still being brief. The recommended convention to follow is
method_condition_expected()
, for example:
getFirstName_generalCase_returnsFirstName
size_empty_returnsZero()
indexOf_singleton_returnsCorrectIndex()
Create the test class for
Course
calledCourseTest
Write a unit test for
getProgramCode
Write a unit test for
getCourseCode
Write a unit test for
getCourseTitle
Write a unit test for
toString
Write a unit test for
equals
Do not write tests for
hashCode
4.2.2. Testing the CourseList
Class
Warning
Writing unit tests for collections is quite difficult for a variety of reasons. For example, consider that collections can have various different states — empty, single element, many elements, duplicate elements.
Consider remove
:
What should happen when
remove
is called on an emptyCourseList
?What should happen when
remove
is called on aCourseList
with one element?What should happen when calling it on a
CourseList
with many elements?What should happen when trying to
remove
an element that does not exist in theCourseList
?What should happen when there are multiple equal
Course
objects to be removed?
Try to test each method as thoroughly as possible.
Write unit tests for
add
Write unit tests for
contains
Write unit tests for
indexOf
Write unit tests for
remove
Write unit tests for
get
Write unit tests for
size
Write unit tests for
toString
Try to write unit tests for
equals
Testing equality on collections is very challenging