This is the lecture note of CS61B - Lecture 3.
In this lecture, we will discuss an important and realistic issue -- Testing.
š¹ Let's think about an important question - how do you know that your code works correctly?
- Run to see if the code works as your expect.
- Pass Autograder (in this course).
- Pass tests written by ourselves.
The last one is the most important one. In the real world, programmers believe their code works correctly because of tests they write themselves.
Ad Hoc Testing vs. JUnit
Let's try to write a method that sorts arrays of Strings and promise its correctness.
With the old way, we will write the sort
method, and use Autograder to verify its correctness. But with the new way which will be taught in this lecture, we will write sort method, as well as our own test for sort method.
Ad Hoc Testing
We will start by writing testSort
first, i.e. writing tests takes precedence over implementing function!
1 | import java.util.Arrays; |
While the single test above isn't a ton of work, writing a suite of such Ad Hoc tests
would be very tedious, as it would entail writing a bunch of different loops and print statements. In the next section, we'll see how the JUnit
library saves us a lot of work.
JUnit
Next, we will do testing with JUnit
, and write tests and the sort method simultaneously.
We will implement Selection Sort in sort method. The idea of selection sort is as follows:
The following code is the final code. If you are curious about the process, please watch lecture videos.
1 | import org.junit.Test; |
1 | public class Sort { |
Unit Testing
Unit Testing is a great way to rigorously test each method of your code, and ultimately to ensure that you have a working project.
The āUnitā part of Unit Testing comes from the idea that you can break your program down into units, or the smallest testable part of an application. Therefore, Unit Testing enforces good code structure (each method should only do āOne Thingā), and allows you to consider all of the edge cases for each method and test for them individually.