Lab 8: Unit Testing

The goal of this lab is to practice creating unit tests for your code. Unit tests will help you develop code more efficiently by quickly identifying bugs.

Although course assignments usually won’t required you to create unit tests, unit testing will make it easier to write programs, especially as assignments become more complicated.

Instructions

In this lab, you will write unit tests to help develop your code for the Traveling Salesperson Problem (TSP) homework. If you are working on the TSP homework with a partner, you should work on this lab together. If you are working on the homework individually, you should work on this lab individually.

Task 1: Create Tour.java

If you haven’t already, spend a few minutes reviewing the instructions for the Traveling Salesperson Problem (TSP) homework.

Next, create Tour.java, based on the method signatures described in the assignment. Write just enough code to get Tour.java to compile. For example:

// Returns the length of this tour.
public double length() {
    return -1.0;
}

Notice that we return -1.0, which will never be correct, to make it clear that this method hasn’t been implemented yet.

Task 2: Run ExampleTests

First, open the Traveling Salesperson Problem (TSP) starter files in IntelliJ.

Next, open the “Run” menu, select “Run …”, then select “All in COS 126” or “ExampleTests”. This will recompile your code, then run the tests in the ExampleTests class.

Run All in COS 126

The bottom of the IntelliJ window should show that all the tests passed.

Tests passed: 1 of 1 test

Task 3: Create tests for your own code

Your assignment is to write unit tests for your homework code. I recommend creating a TourTests class in the test directory.

You should write unit tests using JUnit 5 Jupiter (version 5.4.2). You may find it helpful to consult ExampleTests, the slides, and the resources linked below:

Note: It’s okay to write tests before implementing the Tour class – this is known as test-driven development (TDD). In this case, your tests should fail until you finish implementing Tour.

Hints:

Submit

Complete the “Lab 8: Unit Testing” quiz on Canvas. You should submit a screenshot showing:

This lab will be graded for completion, as part of your attendance and participation grade. However, to be counted towards your grade, you must write and run at least one unit test.

If you worked with a partner, each of you should submit the quiz on Canvas, since there isn’t an easy way to join groups on Canvas.