Object-Oriented Programming with Java · Lecture Notes
Chapter 7: Testing and Debugging
A program that compiles is not necessarily a program that works. The compiler checks only the syntax rules; it cannot know whether the program does what it was meant to do. That answer comes from testing. Testing systematically checks whether a program shows the expected behavior. When a test fails, debugging begins: the cause of the failure is found and fixed. This note first separates the notions of error, defect, and failure, and then introduces the test levels from unit to acceptance. At the center is automated unit testing with JUnit 5: assertion methods, @BeforeEach, exception tests, the test lifecycle, and parameterized tests. Boundary values, regression testing, and test-driven development complete the picture of good test design. The second half covers the debugger, breakpoints, stepping commands, and jdb. The note ends with profilers, code coverage, static analysis, property-based testing, Selenium, and memory analysis tools.
Learning outcomes
- Test levels
- Distinguish unit, module, sub-system, system, and acceptance testing, and explain what each one verifies.
- Unit testing with JUnit
- Write automated tests with
@Test,@BeforeEach, and assertion methods such asassertEqualsandassertThrows; read the message of a failing test. - Good test design
- Choose boundary values, write parameterized tests, keep tests deterministic and repeatable, and explain the value of regression testing.
- Debugging
- Set a breakpoint, step through the program (Step Into / Over / Out), and watch variables to find the source of a bug.
- Analysis tools
- Know which question each of these answers: profiler, code coverage, static analysis (SpotBugs), property-based testing, Selenium, Memory Analyzer, and VisualVM.
- The right tool for the right question
- Decide whether a given problem calls for a test, a debugger, or a profiler.
7.1The foundations of testing and debugging
A student compiles a homework program, tries a few numbers, sees that the results look right, and hands it in. The instructor runs it with negative numbers, an empty array, or a very large input, and the program crashes or returns a wrong result. The student's quick try was also a test, but it was random and incomplete. This note is about making that try systematic, repeatable, and automatic.
7.1.1Why test?
Many sayings circulate about testing in the software world. The software tester Michael Bolton stresses that the goal of testing is less to hunt for bugs than to make sure the system works as expected. An old joke among programmers calls a bug "an undiscovered feature." The saying that treats quality as a habit rather than an act is usually attributed to Aristotle; it is in fact Will Durant's reading of Aristotle. Shipping software without testing is also often compared to Russian roulette.
The most famous of these sayings belongs to Edsger W. Dijkstra. According to Dijkstra, testing can show the presence of bugs, but never their absence. This sentence draws the limit of testing clearly. However large a test suite is, it says something only about the inputs that were tried. One of the billions of untried inputs may crash the program.
Testing is the systematic check of whether a program shows the expected behavior. The program is given selected inputs, and the result it produces is compared with the expected result. If the results agree, the test passes; if not, it fails.
The words "expected result" in the definition are important. To write a test, one must first know what the program is supposed to do. "A method that adds two numbers should return 5 for 2 and 3" is an expectation; the test turns that expectation into code. A program whose expectation is unclear cannot be tested. For this reason, writing tests often helps to clarify a program's requirements as well.
No test suite proves that a program is free of defects, but well-chosen tests raise confidence considerably. If a method shows the expected behavior on normal inputs, on boundaries, and on invalid inputs, it is likely to work correctly on the remaining inputs too. The value of a test lies in producing this confidence cheaply and quickly.
7.1.2Error, defect, failure
In everyday language, the word "bug" is used for everything: the programmer's misunderstanding, the wrong line in the code, and the wrong result on the screen are all called a bug. Software engineering gives these three things separate names. The distinction makes it easier to understand what testing and debugging each look for.
An error is a mistake in the programmer's mind: a wrong assumption, a forgotten case. A defect (or bug) is the wrong line of code in which that mistake shows up. A failure is the wrong behavior that appears when the defective code runs: wrong output, a crash, a freeze.
Figure 7.1 shows the chain from left to right. Each link of the chain lives in a different place. The error is in the programmer's head, the defect is in the source code, and the failure is in the behavior of the running program. Not every defect causes a failure. If the defective line never runs, or gives a wrong result only for rare inputs, the program may look fine for a long time.
A programmer writes a method that finds the largest element of an array. The variable that holds the maximum is initialized to 0: int best = 0;. The three links in this program are as follows.
Error: the programmer assumed that "the array contains at least one positive number." For temperature readings, this assumption does not hold in winter.
Defect: the line int best = 0; in the code. If all elements are negative, no element can exceed 0.
Failure: for temperatures {-5, -2, -8}, the screen shows Highest: 0. The value 0 is not even in the array.
The same method gives the correct result (9) for {3, 9, 4}. The defect turns into a failure only when all elements are negative. For this reason, a try with positive numbers alone never exposes the defect.
7.1.3Testing versus debugging
Testing and debugging are often confused. They serve the same goal but answer different questions. Testing asks "does the program work?" Debugging asks "why does it not work?" once a failure is known to exist.
Debugging is the process of finding and fixing the cause of a known failure, that is, the defective line. The tool used for this is called a debugger.
| Testing | Debugging | |
|---|---|---|
| Goal | Check whether the program works as expected | Find and fix the cause of a known failure |
| Question | "Does it work?" | "Why does it not work?" |
| Result | Pass / fail (✔ / ✘) | The faulty line and its fix |
| Tools | JUnit, Selenium, code coverage | Debugger, stack trace, println |
| When | Continuously, after every change | When a test fails or a user reports a bug |
Table 7.1 also shows how the two activities follow each other. Tests run continuously and report a failure. When a failure is seen, debugging steps in and finds the defect. After the defect is fixed, the tests run again: they confirm that the fix worked and that nothing else broke. A good software process repeats this cycle many times.
The "stack trace" in the table is the list of calls that the JVM prints when an exception is not caught. It shows which method threw the exception at which line and who called that method. In debugging, this is usually the first piece of information to look at.
7.2Test levels
A piece of software consists not of a single method but of hundreds of interconnected classes. For this reason, testing is not done in a single step either. First the smallest parts are tested one by one, then the parts are tested working together, and finally the whole system is checked from the user's point of view. Each step is a different test level.
7.2.1The levels of testing
Figure 7.2 shows the five levels as a pyramid. The shape of the pyramid is deliberate. The base is wide because unit tests are cheap and are written in large numbers. The top is narrow because acceptance tests are expensive, slow, and few. Going from the bottom to the top, the part under test grows.
Unit testing focuses on individual, independent components: a class or a method. It makes sure that each component works correctly on its own. For example, does the withdraw() method of a BankAccount class throw an exception when the balance is insufficient? Unit testing examines the smallest part; it is the most numerous and the fastest test.
Module testing examines a module made up of related components. It verifies that the components inside the module fit together and work together. For example, do the classes Account, Transaction, and Receipt carry out a money transfer correctly together? Even if every class is correct on its own, the cooperation among them may be wrong.
Sub-system testing looks for interface mismatches between sub-systems. It checks the communication and the data flow between components. For example, do the account sub-system and the database sub-system use the same date format? If one expects day/month/year and the other year-month-day, each sub-system works flawlessly alone, but together they produce a wrong record.
System testing examines the whole system as one. Both the functional requirements (what the system does) and the non-functional requirements (speed, security, usability) are checked. "Does a transfer complete in under 2 seconds with 1000 concurrent users?" is a system-testing question. No unit test can answer it.
Acceptance testing examines the system with real data instead of simulated data. It verifies the system's usability and performance in the real world. Acceptance testing is done together with the users. Alpha testing takes place in the developer's environment, beta testing in the user's own environment. In the end, a single question is answered: can the customer say "I accept this system"?
7.2.2The levels at a glance
| Level | What does it test? | Who does it? | Data |
|---|---|---|---|
| Unit | A single class / method | Developer | Small, hand-picked |
| Module | A few classes working together | Developer | Scenario data |
| Sub-system | Interfaces between sub-systems | Developer, test team | Scenario data |
| System | The whole system; speed, security | Test team | Close to real |
| Acceptance (alpha / beta) | Customer requirements | Together with the user | Real data |
Table 7.2 also shows who owns each level. The developer writes the lower levels personally; at the higher levels a separate test team and finally the customer come into play. The data also gets closer to reality as one moves up.
The most important difference between the levels is cost. A bug at a low level is found cheaply and quickly. When a unit test fails, the location of the defect is almost known: a single method. If the same bug shows up in acceptance testing or in the user's hands, one first has to search for which part it comes from, then fix it, and then retest the whole system. The cost of the fix grows multiplicatively. For this reason, the aim is to catch bugs as low as possible.
Which level catches each of the following problems most directly?
(a) The calculateInterest() method forgets to divide the percentage by 100. This is a logic error in a single method: unit testing.
(b) The Account class expects the amount in kuruş, while the Receipt class expects it in lira. This concerns the two classes working together: module testing.
(c) The payment sub-system sends dates as day/month/year, while the reporting sub-system sends them as year-month-day. This lies at the interface where the sub-systems meet: sub-system testing.
(d) The system stops responding with 500 users. This is a non-functional requirement: system testing.
(e) The customer says the report does not fit their accounting routine. This is a real user requirement: acceptance testing.
7.2.3Black-box and white-box testing
Besides their levels, tests are also divided in two according to whether they look inside the code.
Black-box testing is testing done with only the input and the expected output, without looking inside the code. The program is seen from outside as a closed box. White-box testing, on the other hand, is done with knowledge of the code's structure; the aim is to execute every branch and every loop at least once.
Acceptance and system tests are mostly black-box tests. The customer does not read the code; they only check whether the system does what they want. Unit tests and code coverage, on the other hand, use the white-box view. If a method contains an if, a good unit test suite exercises both the true and the false branch of that if. The two views complement each other. Black-box testing starts from the requirements and asks "what should it do?" White-box testing starts from the code and asks "which path have I never tried?"
7.3Unit testing and JUnit
The base of the test levels is unit testing, and it is also the test a programmer writes most often. In Java, unit tests are almost always written with the JUnit framework. To see why JUnit is needed, let us first look at what testing without it is like.
7.3.1Testing by hand
The class to be tested is a simple calculator with two methods.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}Someone new to programming writes a main method to try this class, calls the methods, and prints the results on the screen.
public class ManualTest {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("2 + 3 = " + calc.add(2, 3));
System.out.println("2 * -3 = " + calc.multiply(2, -3));
// Correct? We look at the screen and decide.
}
}2 + 3 = 5
2 * -3 = -6The output looks right: 2 + 3 = 5 and 2 × (−3) = −6. But the decision "it looks right" is made not by the program but by the human looking at the screen. The comment line in the code admits as much. This method has four basic problems.
- The human eye decides whether the result is correct. The eye gets tired and makes mistakes; it is very easy to overlook the difference between 0.30000000000000004 and 0.3.
- When the code changes, everything has to be tried by hand again. Nobody does that every time.
- The test code stays inside
mainand is deleted when the work is done. The effort spent is lost. - For a hundred methods, a hundred lines of output must be read. In a large project this is practically impossible.
The solution is simple: the expected value is also written into the code, and the comparison is left to the computer. The program decides by itself: "I expected 5, I got 5" or "I expected 5, I got 6." This is called an automated unit test.
A unit test is an automated test that checks a method or a class in isolation. The test calls the method with a known input, compares the result with the expected value, and makes the decision itself: pass or fail.
7.3.2The JUnit framework
JUnit is the most widely used unit testing framework for Java. A framework is a ready-made library that makes a particular job easier and that itself calls the programmer's code. Tests are written as ordinary Java methods; JUnit finds them, runs them, and reports the results. The programmer does not write main and does not worry about who calls the test methods in what order.
In Java, a unit usually means a class. The tests check the methods of that class one by one. JUnit was designed basically for unit testing, but it is flexible. It can also be used for module testing in scenarios involving several classes, and for system testing in system-level interactions. IntelliJ IDEA, Eclipse, NetBeans, VS Code, and build tools such as Maven and Gradle run JUnit tests directly.
| Version | How is a test written? |
|---|---|
| JUnit 3 | Inheriting from the TestCase class; methods whose names start with test |
| JUnit 4 | The @Test annotation, the org.junit package |
| JUnit 5 | @Test, the org.junit.jupiter.api package; lambdas, parameterized tests |
Table 7.3 summarizes the development of JUnit. JUnit 3 recognized tests by inheritance and a naming convention. JUnit 4 started to use annotations instead. An annotation is a note that starts with @ and gives information to the compiler or to a tool; @Override is also an annotation. This note uses JUnit 5. The part of JUnit 5 in which tests are written is called Jupiter; the word jupiter in the package names comes from this. In a project that uses Gradle, JUnit 5 is added with the following line:
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")In Maven and Gradle projects, files follow a fixed layout. Test classes go in the src/test/java folder, and the classes under test go in the src/main/java folder. This way the test code is compiled and run together with the program, but does not end up in the package that goes to the end user.
7.3.3The first JUnit 5 test
Let us now turn the manual try written for Calculator into a JUnit test.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
@Test
void addsTwoNumbers() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
@Test
void multipliesByNegative() {
Calculator calc = new Calculator();
assertEquals(-6, calc.multiply(2, -3));
}
}Let us go through the code line by line. The first line imports the @Test annotation. The import static in the second line imports the static method assertEquals of the Assertions class. This way one does not have to write Assertions.assertEquals(…) every time. The test class is named by adding Test to the name of the class under test: CalculatorTest. This is not a rule, but it is a common habit.
Every test method in the class is marked with @Test. This annotation tells JUnit "this method is a test." A test method is void and takes no parameters. No main is needed. In JUnit 5, the test class and its methods do not have to be public; package access is enough.
Each test method creates an object, calls a method, and checks the result with assertEquals(expected, actual). The order of the parameters matters: the expected value comes first, then the actual result. If the values are equal, the method returns silently and the test passes (✔). If they are not equal, it throws AssertionFailedError and the test fails (✘). When these two tests are run, the report looks like this:
✔ addsTwoNumbers()
✔ multipliesByNegative()
2 tests · 2 passed · 0 failedThe names of the test methods read like sentences: addsTwoNumbers, multipliesByNegative. This is a deliberate choice. When a test fails, the name in the report tells you at once what broke. A name such as test1 only says "something broke."
Forgetting the import static line. Without this line, the assertEquals call does not compile:
import org.junit.jupiter.api.Test;
class ImportTest {
@Test void t() { int x = 5; assertEquals(5, x); }
}ImportTest.java:3: error: cannot find symbol
@Test void t() { int x = 5; assertEquals(5, x); }
^
symbol: method assertEquals(int,int)
location: class ImportTest
1 errorThe compiler looks for a method named assertEquals in the test class and cannot find it. The fix is to add the line import static org.junit.jupiter.api.Assertions.*;.
7.3.4Assertion methods
An assertion is a statement that compares an expected result with the actual one, or checks an assumption. In JUnit 5, the assertion methods are the static methods of the org.junit.jupiter.api.Assertions class. If an assertion fails, the method throws AssertionFailedError and the test fails.
assertEquals is the most frequently used assertion, but it is not the only one. Table 7.4 lists the most common assertion methods. All the examples in the last column of the table pass; each of them was tried by running it with JUnit 5.11.
| Method | When does it pass? | Example (all pass) |
|---|---|---|
assertEquals(e, a) | e and a are equal (equals) | assertEquals(5, 2 + 3) |
assertEquals(e, a, delta) | For floating-point numbers, the difference is ≤ delta | assertEquals(0.3, 0.1 + 0.2, 1e-9) |
assertNotEquals(u, a) | Not equal | assertNotEquals(4, 2 + 3) |
assertTrue / assertFalse | The condition is true / false | assertFalse("abc".isEmpty()) |
assertNull / assertNotNull | The value is null / is not null | assertNotNull("x") |
assertSame(a, b) | The same object (==) | assertSame(s, s) |
assertArrayEquals | Arrays are equal element by element | assertArrayEquals(new int[] {1, 2}, new int[] {1, 2}) |
assertThrows(T.class, code) | The code throws an exception of that type | assertThrows(ArithmeticException.class, () -> …) |
assertAll(…) | All assertions (every one is tried) | assertAll(() -> …, () -> …) |
fail("message") | Never; fails the test on purpose | fail("not written yet") |
There is a detail behind every row of the table. assertEquals uses the equals method for objects; for this reason, two Strings with the same contents are considered equal. assertSame, in contrast, compares with == and passes only for two references that point to the same object. For arrays, assertEquals is misleading. The equals method of arrays comes from Object and compares only references. Two separate arrays with the same contents are therefore not considered equal:
assertEquals(new int[] {1, 2}, new int[] {1, 2}); /* fails */expected: [I@4a22f9e2<[1, 2]> but was: [I@3c419631<[1, 2]>In the message, [I@4a22f9e2 shows the type of the array ([I: an int array) and its identity code; the [1, 2] inside the square brackets is its contents. JUnit adds this detail because the text forms of the two values are the same. The contents are the same; the objects are different. To compare arrays element by element, use assertArrayEquals. The identity codes change on every run.
Floating-point numbers call for separate care. 0.1 and 0.2 cannot be represented exactly in binary; their sum is not 0.3 but 0.30000000000000004. For this reason, a tolerance is given as the third parameter for floating-point numbers. The call assertEquals(0.3, 0.1 + 0.2, 1e-9) passes because the difference between the two values is smaller than 10−9. If the tolerance is forgotten, the test fails:
expected: <0.3> but was: <0.30000000000000004>Most assertion methods also take an optional message as the last parameter. When a test fails, the message is added to the front of the report and explains what went wrong. The call assertEquals(4, 2 + 3, "wrong sum") fails with this message:
wrong sum ==> expected: <4> but was: <5>assertAll groups several assertions together. When ordinary assertions are written one after another, the first failing assertion ends the test; the later ones never run. assertAll, on the other hand, runs all the assertions and reports all the failing ones together:
@Test
void twoAssertions() {
assertAll(
() -> assertEquals(4, 2 + 3),
() -> assertEquals(7, 3 + 3));
}org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures)
org.opentest4j.AssertionFailedError: expected: <4> but was: <5>
org.opentest4j.AssertionFailedError: expected: <7> but was: <6>Both assertions have failed, and the report shows both at once. When you check several fields of an object at the same time, this feature saves time: you see which fields are wrong in a single run. The parameters of assertAll are lambda expressions. A lambda expression is a small anonymous function written in the form () -> …; here it means "a piece of code to be run."
Writing the expected and the actual value the wrong way around. assertEquals(calc.add(2, 3), 6) also compiles and runs, but when it fails the message reads backwards: expected: <5> but was: <6>. The report seems to say "the method returned 6," although the method returned 5. Debugging with the wrong message goes to the wrong place. The rule: expected first, then actual.
7.3.5The class under test: BankAccount
A realistic test example needs a somewhat richer class. The BankAccount class keeps a balance and checks its input in deposit and withdrawal operations.
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Invalid amount");
}
balance += amount;
}
public void withdraw(double amount) {
if (amount > balance) {
throw new IllegalStateException("Insufficient funds");
}
balance -= amount;
}
public double getBalance() {
return balance;
}
}The deposit method rejects a zero or negative amount with IllegalArgumentException. The withdraw method rejects an amount larger than the balance with IllegalStateException. The choice of the two exceptions is meaningful too. A negative amount is an invalid argument. Insufficient funds, on the other hand, means that it is not the argument but the object's current state that does not allow the operation.
Before writing tests, one thinks about which behaviors of the class are to be tested. Table 7.5 lists these behaviors for an account with an initial balance of 100.
| Call | Expected | Kind |
|---|---|---|
deposit(50) | balance 150 | normal case |
withdraw(30) | balance 70 | normal case |
withdraw(500) | IllegalStateException; balance stays 100 | invalid input |
deposit(-10) | IllegalArgumentException | invalid input |
deposit(0) | IllegalArgumentException | boundary |
withdraw(100) | balance 0, no exception | boundary |
Each row of the table becomes a separate test method. The rows fall into three groups: normal cases, invalid inputs, and boundaries. Testing only the normal cases is easy and very common; but bugs are mostly in the other two groups. The withdraw(100) row is a good example. If the condition had mistakenly been written as amount >= balance instead of amount > balance, withdrawing the entire balance would throw an exception. Only the input exactly on the boundary catches this defect.
7.3.6The structure of a test: arrange, act, assert
A well-written test method has three parts. This pattern is known by the initials AAA (Arrange, Act, Assert).
class AaaTest {
@Test
void withdrawReducesBalance() {
// Arrange
BankAccount acct = new BankAccount(100);
// Act
acct.withdraw(30);
// Assert
assertEquals(70.0, acct.getBalance(), 0.001);
}
}In the arrange part, the objects and data needed for the test are set up: an account with a balance of 100. In the act part, the method under test is called once: withdraw(30). In the assert part, the result is compared with the expected one: the balance should be 70. Because the balance is a double, a tolerance of 0.001 is given as the third parameter.
The AAA pattern makes a test readable. The reader sees at a glance what the test sets up, what it does, and what it expects. One consequence of the pattern is this: each test checks a single behavior. If a test has more than one "act" step, it is really several tests and should be split. This way, when a test fails, it is immediately clear which behavior broke.
7.3.7Shared setup: @BeforeEach
The tests written for BankAccount all start with the same setup: an account with a balance of 100. Writing this line separately in every test is both repetition and a source of mistakes. JUnit offers the @BeforeEach annotation for shared setup.
class BankAccountTest {
private BankAccount acct;
@BeforeEach
void setUp() {
acct = new BankAccount(100);
}
@Test
void depositIncreasesBalance() {
acct.deposit(50);
assertEquals(150.0, acct.getBalance(), 0.001);
}
@Test
void overdraftThrows() {
assertThrows(IllegalStateException.class,
() -> acct.withdraw(500));
assertEquals(100.0, acct.getBalance(), 0.001);
}
}acct is now a field of the test class. The setUp method, marked with @BeforeEach, runs before every test and assigns a new account to this field. This way every test starts with a fresh, clean account with a balance of 100.
There is a very important detail here. JUnit creates a new object of the test class for every test method. The depositIncreasesBalance test raises the balance to 150, but this change affects only the account in that test's object. The overdraftThrows test runs in its own test object with its own account. The tests do not affect each other.
The second test uses assertThrows. This method runs the code in its second parameter and expects that code to throw an exception of the type given in the first parameter. () -> acct.withdraw(500) is a lambda expression: it does not run immediately but is handed to assertThrows as "a piece of code to be run." assertThrows runs the code inside itself and catches the exception. Because the exception is caught, the test continues, and the second assertion checks that the balance has not changed. Seeing that an invalid operation did not corrupt the object is as important as seeing that the exception was thrown.
When these two tests are run, both pass:
✔ overdraftThrows()
✔ depositIncreasesBalance()
2 tests · 2 passedThe order in the report is not the order in the source code. By default, JUnit 5 orders the test methods with an algorithm that is deterministic but deliberately not specified. This order is the same on every run, but it does not have to match the order in the code.
7.3.8Code trace: how does JUnit run tests?
Let us trace the execution of the BankAccountTest class step by step. At each step we will look at the objects on the heap: the test object and the BankAccount object it points to.
@Test methods in the class and creates a new test object for the first test. The acct field is still null.In the first step, JUnit inspects the class with a mechanism called reflection and finds the methods marked with @Test. It then calls the no-argument constructor of the test class to create a test object. The acct field of this object holds its default value, null (Figure 7.3).
@BeforeEach runs before the test: a new account is created, balance 100.In the second step, setUp runs and the acct field points to a new BankAccount object. Next it is JUnit's turn: overdraftThrows runs first. assertThrows calls the lambda; withdraw(500) throws IllegalStateException because 500 > 100. The exception is of the expected type, so assertThrows passes. The balance is still 100; the second assertion passes as well (Figure 7.5).
assertThrows passes. The balance has stayed at 100, and the second assertion passes too.For the second test, JUnit creates a brand-new test object (#2). The previous test object and its account are no longer used; the garbage collector will clean them up in due course. @BeforeEach runs again, and this test also starts with an account whose balance is 100. With the call deposit(50), the balance becomes 150. In the assertion, 150.0 is compared with 150.0; the difference is less than 0.001, and the test passes (Figure 7.6).
| Step | Event | Test object | acct | Balance |
|---|---|---|---|---|
| 1 | Test object created | #1 | null | — |
| 2 | @BeforeEach | #1 | new account | 100 |
| 3 | withdraw(500), exception | #1 | same | 100 |
| 4 | both assertions pass ✔ | #1 | same | 100 |
| 5 | New test object | #2 | null | — |
| 6 | @BeforeEach | #2 | new account | 100 |
| 7 | deposit(50) | #2 | same | 150 |
| 8 | assertion passes ✔ | #2 | same | 150 |
Table 7.6 summarizes the trace. The most important row of the table is step 5: JUnit does not reuse the previous object for the second test. This design guarantees that tests are independent of each other. The state one test leaves behind does not leak into the next. This guarantee holds only for instance fields; static fields belong to the class, and all test objects share the same field. If a test increments a static counter, the value seen by the next test changes as well.
7.3.9Testing exceptions
Checking that invalid input is rejected is as important as checking valid input. A method that accepts a negative amount can be far more dangerous than one that gives a wrong result. assertThrows is made for this job.
class BankExceptionTest {
@Test
void overdraftMessage() {
BankAccount acct = new BankAccount(100);
IllegalStateException e = assertThrows(
IllegalStateException.class, () -> acct.withdraw(500));
assertEquals("Insufficient funds", e.getMessage());
}
@Test
void negativeDepositRejected() {
BankAccount acct = new BankAccount(100);
assertThrows(IllegalArgumentException.class,
() -> acct.deposit(-10));
}
@Test
void wrongExpectation() {
BankAccount acct = new BankAccount(100);
assertThrows(IllegalStateException.class,
() -> acct.withdraw(50));
}
}assertThrows does not merely check that an exception was thrown; it also returns the exception object that was thrown. The first test stores this object in the variable e and additionally verifies that its message is "Insufficient funds". The second test checks that a negative deposit is rejected. The third test is deliberately wrong: withdrawing 50 TL is a valid operation and throws no exception. The result is as follows:
✔ overdraftMessage()
✔ negativeDepositRejected()
✘ wrongExpectation()
Expected java.lang.IllegalStateException to be thrown, but nothing was thrown.
3 tests · 2 passed · 1 failedThe message is clear: IllegalStateException was expected, but no exception was thrown. assertThrows fails in two cases. The first is that no exception is thrown at all, as here. The second is that an exception of a different type than expected is thrown. For example, assertThrows(IllegalStateException.class, () -> acct.deposit(-10)) fails with this message:
Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.IllegalArgumentException>assertThrows accepts subtypes as well. Integer.parseInt("abc") throws a NumberFormatException; this class is a subclass of IllegalArgumentException. For this reason, assertThrows(IllegalArgumentException.class, () -> Integer.parseInt("abc")) passes. If the exact type is wanted, assertThrowsExactly is used; this method fails on the same call.
In JUnit 4, exception tests were written differently: @Test(expected = IllegalStateException.class). With this form, the test passes if any line of the test method throws the exception. assertThrows, on the other hand, states exactly which call the exception is expected from and gives access to the exception object.
7.3.10The test lifecycle
@BeforeEach is only one of JUnit's lifecycle annotations. Together, the four decide which code runs when around the tests.
class LifecycleTest {
@BeforeAll
static void start() { System.out.println("BeforeAll"); }
@BeforeEach
void setUp() { System.out.println(" BeforeEach"); }
@Test
void testA() { System.out.println(" testA"); }
@Test
void testB() { System.out.println(" testB"); }
@AfterEach
void cleanUp() { System.out.println(" AfterEach"); }
@AfterAll
static void finish() { System.out.println("AfterAll"); }
}The only purpose of this class is to print the order in which the methods run. The output is as follows:
BeforeAll
BeforeEach
testA
AfterEach
BeforeEach
testB
AfterEach
AfterAll| Annotation | When does it run? | Typical use |
|---|---|---|
@BeforeAll | Once before all tests (static) | Opening an expensive shared resource |
@BeforeEach | Before every test | Rebuilding the test objects |
@AfterEach | After every test (even if the test fails) | Deleting a temporary file |
@AfterAll | Once after all tests (static) | Closing the shared resource |
The output confirms the rules in Table 7.7. BeforeAll and AfterAll are printed once, at the very beginning and the very end. BeforeEach and AfterEach run once around each test; since there are two tests, they appear twice. It matters that @AfterEach runs even if the test fails: this is why cleanup work is put there. An exception thrown in the middle of a test does not leave a temporary file lying around.
The @BeforeAll and @AfterAll methods must be static. The reason can be seen in Table 7.6: JUnit creates a separate object for each test. There is no test object yet on which to call the method that is to run "once before all tests"; the method must belong to the class. If this rule is forgotten, JUnit runs none of the tests in the class and gives this error:
class NonStaticTest {
@BeforeAll void start() { }
@Test void t() { }
}org.junit.platform.commons.JUnitException: @BeforeAll method 'void NonStaticTest.start()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).The @TestInstance(Lifecycle.PER_CLASS) annotation suggested by the message tells JUnit to use a single test object for all the tests. Then @BeforeAll can be an instance method; but the independence of the tests also weakens. The default behavior is usually safer.
The order of the tests among themselves is fixed, but it does not have to match the order in the source code. For this reason, tests are never written to depend on one another. An arrangement such as "first testA opens the account, then testB withdraws money from that account" breaks when the order changes.
7.3.11From red to green: a failing test
The real value of a test shows when it catches a bug. The first version of the max method from the fault-chain example is this:
public class ArrayUtils {
public static int max(int[] arr) {
int best = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > best) {
best = arr[i];
}
}
return best;
}
}The code compiles and looks right at first glance. The loop compares every element with best and updates best when it finds a larger one. Let us write two tests for this method: one with an array of positive numbers and one with an array of all negative numbers.
class ArrayUtilsTest {
@Test
void positiveArray() {
int[] arr = {3, 9, 4};
assertEquals(9, ArrayUtils.max(arr));
}
@Test
void allNegativeArray() {
int[] arr = {-5, -2, -8};
assertEquals(-2, ArrayUtils.max(arr));
}
}✔ positiveArray()
✘ allNegativeArray()
org.opentest4j.AssertionFailedError: expected: <-2> but was: <0>
2 tests · 1 passed · 1 failedThe message of the failing test has two parts. expected shows the expected value (−2), and but was shows the value the method actually returned (0). The value 0 is not even in the array. This clue almost gives away the location of the defect: the value 0 did not come from inside the array but from somewhere else. The only candidate is the initialization best = 0. When all elements are negative, no element can exceed 0, and best is never updated.
In the testing world, a failing test is called red and a passing test green; IDEs show the results in these colors. The corrected version of the defect is this:
public class ArrayUtils {
public static int max(int[] arr) {
int best = arr[0]; // first element
for (int i = 1; i < arr.length; i++) {
if (arr[i] > best) {
best = arr[i];
}
}
return best;
}
}The maximum is now initialized with the first element of the array. The loop also starts at index 1, because element 0 is already in best. The same two tests are run again, and both pass:
✔ positiveArray()
✔ allNegativeArray()
2 tests · 2 passedi | arr[i] | Version 1: condition | Version 1: best | Fixed: condition | Fixed: best |
|---|---|---|---|---|---|
| start | — | — | 0 | — | −5 |
| 0 | −5 | −5 > 0 false | 0 | (loop starts at 1) | −5 |
| 1 | −2 | −2 > 0 false | 0 | −2 > −5 true | −2 |
| 2 | −8 | −8 > 0 false | 0 | −8 > −2 false | −2 |
| return | 0 ✘ | −2 ✔ |
Table 7.8 shows the difference between the two versions step by step. In the first version, the condition is never true in any iteration. In the fixed version, in the first iteration (i = 1) −2 turns out to be greater than −5, and best is updated. The loop runs as many times as the length of the array in the first version and one fewer time in the fixed version; the time cost is O(n) and the extra memory is O(1).
This test has one more value: it is now permanent. If the code is changed again someday and the same defect comes back, the allNegativeArray test catches it immediately. That the same tests are run again after the fix and turn green is the evidence that the fix worked.
The fixed version raises a question for the empty array as well. arr[0] throws ArrayIndexOutOfBoundsException on an empty array. The first version would silently return 0 for the same input, which is also a wrong answer, because an empty array has no largest element. What a method does on empty input must be decided explicitly, and that decision must be tested too, for example assertThrows(ArrayIndexOutOfBoundsException.class, () -> ArrayUtils.max(new int[0])).
7.4Good test design
JUnit makes writing tests easier, but it does not decide which tests to write. The input space of a method is often huge: even a single parameter of type int can take more than four billion values. Trying them all is impossible. Good test design is the art of catching bugs with a small number of well-chosen inputs.
7.4.1Boundary values and equivalence classes
The example method converts a score between 0 and 100 into a letter grade.
public class Grade {
public static String letterGrade(int score) {
if (score < 0 || score > 100) {
throw new IllegalArgumentException("Invalid score: " + score);
}
if (score >= 90) return "AA";
if (score >= 80) return "BA";
if (score >= 70) return "BB";
if (score >= 60) return "CB";
if (score >= 50) return "CC";
return "FF";
}
}The method first rejects out-of-range scores and then tries the thresholds from top to bottom. Which scores should be tested? There are 101 different valid scores; writing all of them is both tedious and unnecessary. The scores 61, 65, and 68 follow the same path and give the same result (CB). If one is right, the others are expected to be right as well.
An equivalence class is a set of inputs that lead to the same behavior in the program. Picking a single representative from an equivalence class is enough. Boundary value analysis, in turn, chooses the end values of each equivalence class and the first values of the invalid region as test inputs.
Why boundary values matter so much is explained by one observation: bugs occur most often at the boundaries. Programmers often mix up > and >=, or < 100 and <= 100. A defect of this kind never shows up for inputs in the middle of a range. A score of 65 gives CB with score >= 60 and with score > 60 alike. The difference appears only exactly on the boundary, at 60.
Figure 7.7 shows the chosen values. Both ends of each range are tested: 49 and 50 enclose the boundary between FF and CC from both sides; 89 and 90 do the same for BA and AA. The first values of the invalid region (−1 and 101) are chosen too, because a defect in the range check is seen only with them. The ends of the valid region (0 and 100) are not forgotten either.
How is a complete set of boundary values built for letterGrade?
Equivalence classes: invalid low (< 0), FF (0–49), CC (50–59), CB (60–69), BB (70–79), BA (80–89), AA (90–100), invalid high (> 100). There are eight classes in total.
Take both ends of each valid class: 0, 49, 50, 59, 60, 69, 70, 79, 80, 89, 90, 100. Add the first values of the invalid region: −1 and 101. That makes 14 inputs.
This set tries only 12 of the 101 possible valid scores, but it tests every threshold from both sides. If any >= had mistakenly been written as >, the lower end of that threshold would give the wrong letter and the test would fail.
7.4.2Parameterized tests
Once the boundary values are chosen, is a separate test method needed for each one? Writing an almost identical method for every value is both long and prone to copy-and-paste mistakes. JUnit 5 offers the parameterized test instead.
class GradeTest {
@ParameterizedTest
@CsvSource({"0, FF", "49, FF", "50, CC", "59, CC",
"60, CB", "89, BA", "90, AA", "100, AA"})
void boundaries(int score, String expected) {
assertEquals(expected, Grade.letterGrade(score));
}
@Test
void outOfRangeRejected() {
assertThrows(IllegalArgumentException.class,
() -> Grade.letterGrade(-1));
assertThrows(IllegalArgumentException.class,
() -> Grade.letterGrade(101));
}
}The @ParameterizedTest annotation states that the same test method will run again and again with different data. The data is supplied with @CsvSource. Each string is one test invocation. The comma-separated values are converted in order into the parameters of the method: in the string "50, CC", "50" is converted to an int and passed to score, and "CC" is passed to expected. The name comes from the CSV (comma-separated values) file format.
Parameterized tests live in the junit-jupiter-params module. The junit-jupiter package added to Gradle includes this module as well; nothing extra needs to be added. When the class is run, the report shows each data row as a separate test:
boundaries(int, String)
✔ [1] 0, FF
✔ [2] 49, FF
✔ [3] 50, CC
✔ [4] 59, CC
✔ [5] 60, CB
✔ [6] 89, BA
✔ [7] 90, AA
✔ [8] 100, AA
✔ outOfRangeRejected()
9 tests · 9 passedThe report has 9 tests: the 8 invocations of the parameterized test and the ordinary test that checks the out-of-range scores. Had a row failed, the sequence number and the values in the square brackets would immediately show which data caused the problem. The out-of-range test calls assertThrows twice: once for −1 and once for 101.
Compared with the complete set in Example 7.3, this test skips a few boundaries: the pairs 69/70 (CB/BB) and 79/80 (BB/BA) are not in the list. The BB range is never tested. Adding four more strings to @CsvSource closes this gap; the test method itself does not change at all. This is the real strength of the parameterized test: adding a new case is a one-line job.
7.4.3Code trace: a parameterized test
Let us trace the parameterized test along the score axis. JUnit first reads the 8 strings in @CsvSource; each of them will be a separate test invocation.
"0, FF" is split at the comma; "0" is converted to an int and passed to score, and "FF" is passed to expected. The result is "FF", and the test passes.| Call | score | expected | First true condition | Returned | Role | Result |
|---|---|---|---|---|---|---|
| [1] | 0 | FF | none | FF | first value of the valid region | ✔ |
| [2] | 49 | FF | none | FF | upper end of FF | ✔ |
| [3] | 50 | CC | score >= 50 | CC | lower end of CC | ✔ |
| [4] | 59 | CC | score >= 50 | CC | upper end of CC | ✔ |
| [5] | 60 | CB | score >= 60 | CB | lower end of CB | ✔ |
| [6] | 89 | BA | score >= 80 | BA | upper end of BA | ✔ |
| [7] | 90 | AA | score >= 90 | AA | lower end of AA | ✔ |
| [8] | 100 | AA | score >= 90 | AA | last value of the valid region | ✔ |
Table 7.9 shows which path each call takes inside the method. The row for 49 is interesting: none of the conditions is true, and the method reaches the return "FF" at the bottom. If the condition had mistakenly been written as score > 48 instead of score >= 50, 49 would give CC and [2] would fail. The row for 100 proves that the score > 100 check is written correctly. If the check had mistakenly been score >= 100, a score of 100 would throw an exception.
Suppose score > 50 is mistakenly written instead of score >= 50 in letterGrade. Which row of the parameterized test fails?
49: no condition is true, FF. Expected FF; passes.
50: 50 > 50 is false; the method returns FF. Expected CC; fails: expected: <CC> but was: <FF>.
59: 59 > 50 is true, CC. Expected CC; passes.
Only [3] fails. 49 and 59 cannot see this defect; only the value exactly on the boundary catches the bug.
7.4.4Properties of a good unit test: FIRST
The properties of a good unit test are summarized by the acronym FIRST, formed from their initials.
- F · Fast
- It finishes within milliseconds; thousands of them can be run after every change. A unit test does not use files, the network, or a database. If a test suite takes five minutes, programmers stop running it.
- I · Independent
- It does not depend on another test, on the test order, or on the state left behind by a previous test. JUnit's creation of a new object for every test supports this property.
- R · Repeatable
- It gives the same result on every machine at any time. Variable sources such as randomness and the clock are brought under control.
- S · Self-validating
- The result is ✔ or ✘. No human needs to read and interpret the output.
- T · Timely
- It is written together with the code, or even before the code. A test put off until months later is usually never written.
One more property is added to these five: readability. A descriptive name, the AAA pattern, and one behavior per test make a test readable. A well-written test is a document that shows how the code is to be used. A new programmer learns what the withdraw method does on insufficient funds by reading BankAccountTest.
7.4.5Unit test or integration test?
Real classes often do not work alone. An order class reads prices from a database, writes the result to a file, and sends an e-mail. A test that checks such a class together with the real database is no longer a unit test.
| Unit test | Integration test | |
|---|---|---|
| Scope | A single class / method, in isolation | Several components working together |
| Speed | Milliseconds | Seconds (database, file, network) |
| External dependency | Replaced by a simple fake object (test double) | Real database, file, service |
| Bugs it finds | Local logic errors; the location is immediately clear | Mismatched interfaces, wrong configuration |
An integration test checks components that work together with their real dependencies. Module and sub-system tests are of this kind. In a unit test, on the other hand, an external dependency is replaced by a simple object that imitates it. This object is called a test double; the name comes from the stunt double who takes the actor's place in dangerous scenes. For example, in place of an interface that reads prices from a database, a small class is written that returns a fixed price for every product. The test becomes both faster and independent of the current contents of the database.
Table 7.10 also shows that the two kinds of test do not replace each other. Unit tests find logic errors quickly and show their location exactly. Integration tests verify that the parts are wired together correctly. As in the test pyramid, unit tests are written in large numbers and integration tests in smaller numbers.
Test names should also describe behavior. Of the three names below, the first says nothing; the other two explain which rule was broken when the test fails.
@Test void test1() { … }
@Test void discountForSixItems() { … }
@Test void noDiscountForFive() { … }In a unit test, what is checked is the externally visible behavior, not the internal details of the implementation. What matters about a method is what it returns, not which helper method it calls inside. Tests tied to internal details break at every refactoring, even when the behavior has not changed. A unit test does not use Thread.sleep, the real network, or files; otherwise the test becomes slow and starts to behave randomly. Mutable state, such as a static list, is not shared between tests either.
7.5Regression and automation
The value of a test does not end on the day it is written. As the code changes, the test runs again and checks whether the old behavior is preserved. What makes tests so valuable is that they are automatic and can be rerun after every change.
7.5.1Regression testing
Regression testing is verifying, after changes are made, that everything that worked before still works. Regression means "going backwards": something that had been fixed breaks again. The method is simple: all previously written tests are rerun after every change.
withdraw test fails in version 2: the change has broken an old behavior.Figure 7.10 shows a typical regression. While adding a new feature, the programmer touched the withdraw method and broke it without noticing. Without tests, this defect would be noticed only when a customer could not withdraw money. Regression testing catches the defect right after the change, while the person who made it still has that code in mind.
For regression testing to work, tests must have two properties.
- Deterministic: it must give the same result every time under the same conditions. A test that sometimes passes and sometimes fails is called flaky. A flaky test destroys trust: when it fails, people say "that test again" and move on, and a real bug is overlooked too.
- Repeatable: it must be possible to repeat it in the same way at different times, on different machines, and in different situations. A test that passes only on the programmer's computer says nothing when it fails on the server.
7.5.2Testing code that involves randomness deterministically
How is code that generates random numbers tested? A die class returns a different number between 1 and 6 on every roll; writing the expected result in advance seems impossible. The solution is to move the source of randomness outside the class.
import java.util.Random;
public class Die {
private final Random random;
public Die(Random random) { // injected
this.random = random;
}
public int roll() {
return random.nextInt(6) + 1;
}
}The Die class does not create its own Random object; it receives it through its constructor. This design is called dependency injection: another object that an object needs is supplied from outside. In real use, the program writes new Die(new Random()) and gets different numbers each time. The test, on the other hand, supplies a Random created with a fixed seed.
The Random class does not really produce random numbers but pseudo-random ones. The numbers are derived from a starting value by a formula. This starting value is called the seed. Two Random objects created with the same seed produce the same sequence of numbers. Five rolls made with seed 42 give the following result on every machine and in every run:
3 4 1 3 1class DieTest {
@Test
void sameSeedSameRolls() {
Die d1 = new Die(new Random(42));
Die d2 = new Die(new Random(42));
for (int i = 0; i < 100; i++) {
assertEquals(d1.roll(), d2.roll());
}
}
}The test creates two dice with the same seed and verifies that over 100 rolls the two always give the same number. The test gives the same result in every run; that is, it is deterministic. Had new Random() been written inside the die class, the test would have had no way at all of controlling the seed.
Determinism makes other tests possible too. assertEquals(3, new Die(new Random(42)).roll()) always passes, because the first roll of seed 42 is always 3. Had the same assertion been written with an unseeded new Random(), the test would pass only with probability 1/6: a textbook flaky test. A meaningful test that can be written with an unseeded die checks the range of the result: an assertion such as int x = die.roll(); assertTrue(x >= 1 && x <= 6); holds for every die.
Testing clock-dependent code directly. A "birthday discount" method that calls LocalDate.now() gives a different result depending on the day the test is run. The test passes on the day it is written and fails the next day. The solution is the same as in the die example: the source of the date or time is supplied from outside, and the test uses a fixed date.
7.5.3Automated tests and continuous integration
Code should be checked with automated tests instead of by hand. The effort spent is about the same: for a manual try, too, inputs are chosen and outputs are examined. The difference shows up in the end. Nothing remains from a manual try; from an automated one, a test remains that can be rerun whenever you like. This test can run again on every build and every change.
It is wrong to think that software need not be tested again just because it worked once. Code changes, the libraries in use move to new versions, and the environment the program runs in changes. A program that worked correctly yesterday can break today.
| Manual | Automated | |
|---|---|---|
| Initial cost | Low | Somewhat higher |
| Cost of repetition | The same every time | ≈ 0 |
| Speed | Minutes | Seconds |
| Reliability | Human error | The same every time |
| Regression | Not done in practice | On every change |
| Documentation value | None | Usage examples |
Table 7.11 compares the two approaches. The initial cost of an automated test is somewhat higher: the test code has to be written. But the cost of each repetition is almost zero. If a test is going to be run 100 times, the automated one is far cheaper. Regression testing can in practice be done only with automated tests; no programmer tries a hundred cases by hand after every change.
The last step of automation is for tests to run without anyone asking the programmer. Continuous integration (CI) systems do this. GitHub Actions and Jenkins are common examples of such systems.
Figure 7.11 shows a typical pipeline. The programmer pushes the change to the shared repository (git push). The CI server fetches the code, builds it, and runs all the tests. If one of the tests fails, the change is not merged into the main code and the programmer is notified. In this way no regression can enter the main code unnoticed.
7.5.4Test-driven development
Tests are usually written after the code. Some programmers reverse the order: first the test, then the code.
Test-driven development (TDD) is a development method that writes the test before the code. The method proceeds in short cycles; each cycle has three steps: red, green, refactor.
Figure 7.12 shows the cycle. In the red step, a test is written for a behavior that does not exist yet. The test fails; it may not even compile, since the method has not been written yet. In the green step, the simplest code that will make the test pass is written. The code does not have to be pretty at this step; it is enough for the test to pass. In the refactoring step, the code is cleaned up: duplication is removed and names are fixed. As long as the tests stay green, the behavior is preserved.
How is the letterGrade method developed with TDD?
Cycle 1, red: the test assertEquals("CC", Grade.letterGrade(50)) is written. The Grade class does not exist yet; the test does not compile.
Cycle 1, green: the simplest code is written: return "CC";. The test passes. The code is obviously incomplete, but the only test we have asks for no more than this.
Cycle 2, red: assertEquals("FF", Grade.letterGrade(49)) is added. Since the method always returns CC, the new test fails.
Cycle 2, green: if (score >= 50) return "CC"; return "FF";. Both tests pass.
Each new grade range is a new cycle. In the end, every line of letterGrade has been born from a test, and regression tests accumulate on their own.
The biggest gain of TDD is that it leaves no untested code. A side gain is that it improves design. Because the test is written first, the programmer first thinks of the class as a user would: what should the method be called, which parameters should it take, what should it do on invalid input? A class that is hard to test is usually a badly designed class; TDD makes this visible before any code is written.
7.6Debugging
A test reports a failure: expected: <-2> but was: <0>. But it does not always say which line the defect is in. In a small method, the defect can be found by reading the code; in a program of hundreds of lines, one has to look inside the program while it runs. The tool for this job is the debugger.
7.6.1The debugger
A debugger is a tool that lets you inspect the state of a running program. It stops the program at a chosen line, advances it line by line, and shows the values of variables at any moment. The line at which the program is to stop is called a breakpoint.
With a debugger, you can do the following:
- run the program command by command (line by line);
- see the source code of the running program together with the current line;
- display the values of variables and, if needed, change them;
- add breakpoints to the program and run it up to a breakpoint;
- examine the state of a crashed or halted program through a dump file.
The last item needs a little explanation. When a program crashes or freezes, its state at that moment can be written to a file. In C, this file is called a core file. In Java there are two kinds of dump. A heap dump (an .hprof file) contains all the objects on the heap. A thread dump shows which line each thread is at at that moment. A dump is a snapshot of the program; it can be examined without running the program again.
i = 2, total = 1.Figure 7.13 shows the debugging view of an IDE in simplified form. The program has stopped at the line total += i;. The line has not run yet: in the first iteration of the loop total became 1, and now the second iteration has begun. A program stopped at a breakpoint waits as long as needed. The programmer looks at the variables, moves to the next step, or lets the program continue.
IntelliJ IDEA, Eclipse, NetBeans, and VS Code all have a built-in debugger. A breakpoint is set by clicking next to the line number, and the program is started with the Debug button. A program started with the ordinary Run button does not stop at breakpoints.
A common alternative to the debugger is debugging with println: lines such as System.out.println("i = " + i) are added at suspicious places. This method is fast and works everywhere. But it clutters the code, requires recompiling after every change, and the added lines are often forgotten and never removed. The debugger, on the other hand, does not change the code at all; which variable to watch is decided while the program is running.
7.6.2Breakpoints and stepping commands
Once the program has stopped at a breakpoint, it is advanced with stepping commands. The command names are in English in IDEs; the shortcuts vary from one IDE to another.
| Command | What does it do? | IntelliJ | Eclipse |
|---|---|---|---|
| Breakpoint | The program stops when it reaches this line, before the line runs | Ctrl+F8 | Ctrl+Shift+B |
| Step Over | Runs the line; if it contains a method call, completes the call without entering it | F8 | F6 |
| Step Into | Enters the method call on the line | F7 | F5 |
| Step Out | Finishes the current method and returns to the caller | Shift+F8 | F7 |
| Resume | Runs until the next breakpoint | F9 | F8 |
| Evaluate / Watch | Evaluates an expression (e.g. arr[i] > best) on the spot, or watches it continuously | Alt+F8 | Ctrl+Shift+I |
The commands in Table 7.12 that are most often confused are Step Over and Step Into. Both run the current line. The difference appears when the line contains a method call. Step Into enters that method and stops at its first line. Step Over runs the method in a single step and stops at the next line. If you are sure the called method works correctly, Step Over saves time. If you suspect the defect is inside that method, use Step Into.
The shortcuts follow the default key mapping; the same commands are also reachable from the menu (Run / Debug). There is no need to memorize the shortcuts in the table. It is enough to know what the commands do.
The ordinary breakpoint has two powerful variants. A conditional breakpoint stops only if the given condition is true. If a loop runs 10,000 times and the defect shows up only when i is 999, the condition i == 999 is written on the breakpoint. The program runs through 999 iterations without stopping and stops at exactly the moment you are after. An exception breakpoint stops at the moment a particular exception (e.g. NullPointerException) is thrown. Because it stops where the exception is thrown rather than where it is caught, the current variables have not yet been lost.
7.6.3Code trace: finding the defect with the debugger
This time let us approach the failure in the fault-chain example with the debugger. Without reading the code, starting only from the failure Highest: 0 on the screen, we want to find the defect.
public class FindMax {
public static int max(int[] arr) {
int best = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > best) {
best = arr[i];
}
}
return best;
}
public static void main(String[] args) {
int[] temps = {-5, -2, -8};
int result = max(temps);
System.out.println("Max: " + result);
}
}A breakpoint is set on line 5, on the condition if (arr[i] > best). Another breakpoint is set on the first line of main (13), and the program is started with Debug. The program stops at line 13; one Step Over brings us to the call max(temps) on line 14. Step Into enters max. A new frame is added to the stack; the arr parameter in this frame points to the very same array as temps in main. The array has not been copied; only its reference has been passed. Resume advances the program to the breakpoint.
i = 0, arr[0] = -5, best = 0. The watched expression arr[i] > best evaluates to false.The expression arr[i] > best is added to the watch list. The debugger recomputes this expression at every stop. At the first stop the expression is false: −5 is not greater than 0 (Figure 7.14). Resume moves on to the later iterations of the loop. For i = 1, −2 > 0 is again false; best does not change. For i = 2, −8 > 0 is false too. At this point the suspicion becomes clear: best is never updated.
best is still 0, and 0 is returned. The defect is found: the initial value 0 is wrong if all elements are negative.| Step | Command | Line | i | arr[i] | best | arr[i] > best |
|---|---|---|---|---|---|---|
| 1 | Debug | 13 (main) | — | — | — | — |
| 2 | Step Over | 14 (main) | — | — | — | — |
| 3 | Step Into | 3 | — | — | not yet | — |
| 4 | Resume | 5 | 0 | −5 | 0 | false |
| 5 | Resume | 5 | 1 | −2 | 0 | false |
| 6 | Resume | 5 | 2 | −8 | 0 | false |
| 7 | Step Over (several times) | 9 (return) | — | — | 0 | — |
Table 7.13 summarizes the session. In the third step a new frame is opened; best has not been assigned yet. In the last step the loop ends and we reach the line return best;; the value to be returned is 0. The location of the defect is now clear: int best = 0;. The correct line is int best = arr[0];. When the program is allowed to continue, the failure appears on the screen: Highest: 0.
After the fix, this case is added as a unit test. Every defect found with the debugger is made permanent by a test that catches it. This way, if the same defect comes back, there is no need for the debugger again; the test reports it at once.
7.6.4Step Into, Step Over, Step Out
Let us trace the difference among the three stepping commands in a program with nested method calls.
public class StepDemo {
static int square(int x) {
return x * x;
}
static int sumSquares(int a, int b) {
int sq1 = square(a);
int sq2 = square(b);
return sq1 + sq2;
}
public static void main(String[] args) {
int s = sumSquares(3, 4);
System.out.println("s = " + s);
}
}The line numbers are as follows: line 1 is the class header, line 3 is return x * x;, line 7 is int sq1 = square(a);, line 8 is int sq2 = square(b);, line 9 is return sq1 + sq2;, line 13 is int s = sumSquares(3, 4);, line 14 is println, and line 15 is the closing brace of main. The breakpoint is on line 13, and the program has stopped there. The line has not run yet.
| Command | Line reached | Frames on the stack | Visible variables | Explanation |
|---|---|---|---|---|
| (breakpoint) | 13 | main | — | the line has not run yet |
| Step Into | 7 | main → sumSquares | a = 3, b = 4 | entered sumSquares |
| Step Over | 8 | main → sumSquares | a, b, sq1 = 9 | square(3) ran but was not entered |
| Step Into | 3 | main → sumSquares → square | x = 4 | this time we are inside square(4) |
| Step Out | 8 | main → sumSquares | a, b, sq1 = 9 | square returned 16; the assignment is about to complete |
| Step Over | 9 | main → sumSquares | sq1 = 9, sq2 = 16 | the assignment completed |
| Step Out | 13 | main | — | sumSquares returned 25 |
| Step Over | 14 | main | s = 25 | the assignment completed |
| Step Over | 15 | main | s = 25 | the output was printed: s = 25 |
Table 7.14 shows the difference among the three commands clearly. The first Step Into enters the call to sumSquares and adds a new frame to the stack. The chain of frames in the third column is the call stack. The Step Over that follows does not enter the call square(3) on line 7; it runs the call as a whole and moves to line 8. sq1 is now 9.
On line 8, this time Step Into is chosen, and we enter square(4). There are three frames on the stack. In the square frame only x is visible; a, b, and sq1 are in another frame. Step Out runs the rest of square in a single step and returns to the calling line. The subtle point to notice is this: after Step Out we are still on line 8. The method has returned 16, but this value has not yet been assigned to sq2. The assignment completes only at the next Step Over.
The second Step Out finishes sumSquares and returns to line 13 in main; the return value is 25. The last two Step Overs complete first the assignment (s = 25) and then the output. After that, Resume ends the program.
The program is stopped on line 7 (int sq1 = square(a);) and a = 3. If two Step Overs are made in a row, where are we and what are the variables?
The first Step Over runs square(3) without entering it and completes the assignment: line 8, sq1 = 9.
The second Step Over runs square(4): line 9, sq1 = 9, sq2 = 16.
We never enter square. There are always two frames on the stack: main and sumSquares.
7.6.5Debugging from the command line: jdb
The debuggers of IDEs use the same mechanism behind the scenes: the JVM's debugging interface. The JDK ships with a tool that uses this interface from the command line: jdb (the Java Debugger). jdb does with commands what IDEs do with buttons. It is useful on a server with no IDE installed or on a machine with only terminal access.
public class Jdb {
static int square(int x) {
int result = x * x;
return result;
}
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 3; i++) {
total += square(i);
}
System.out.println("Sum: " + total);
}
}The program adds up the squares of the numbers from 1 to 3: 1 + 4 + 9 = 14. To run it under the debugger, it is first compiled with the -g option and then started with jdb instead of java:
javac -g Jdb.java
jdb JdbThe -g option also writes the names of local variables into the class file. In a class compiled without this option, the locals command cannot show variable names, because the class file contains only slot numbers.
| Command | Meaning |
|---|---|
stop at Class:line | sets a breakpoint |
clear Class:line | removes a breakpoint |
run / cont | starts / continues |
step / next / step up | Step Into / Over / Out |
where | shows the call stack |
locals, print x | shows the local variables, or a single value |
The commands in Table 7.15 map one to one onto the IDE commands. step corresponds to Step Into, next to Step Over, step up to Step Out, and cont to Resume.
jdb can also attach to a running application. For this, the application is started with a special option: java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 MyApp. This option makes the JVM load the debugging agent and listen on network port 5005. suspend=y makes the program wait until a debugger attaches. Then the command jdb -attach 5005, or an IDE, connects to this port. This is how one debugs a program on a remote server.
7.6.6A jdb session
The session below was captured by running it with JDK 21; the lines that start with > and main[1] are the jdb prompt.
> stop at Jdb:4
Deferring breakpoint Jdb:4.
It will be set after the class is loaded.
> run
VM Started: Set deferred breakpoint Jdb:4
Breakpoint hit: "thread=main", Jdb.square(), line=4 bci=4
main[1] where
[1] Jdb.square (Jdb.java:4)
[2] Jdb.main (Jdb.java:10)
main[1] locals
Method arguments:
x = 1
Local variables:
result = 1The command stop at Jdb:4 sets a breakpoint on line 4, on return result;. Because the class has not been loaded yet, jdb defers the breakpoint and places it when the class is loaded. run starts the program. The program stops when it reaches line 4. The bci=4 in the message shows at which byte of the method's bytecode we are stopped; when working at the source level, this number does not matter.
The where command shows the call stack: square (line 4) on top, and below it the main (line 10) that called it. locals lists the variables in the current frame. x = 1 is the method argument, and result = 1 is the local variable. This is the first iteration: square(1) has been called for i = 1.
main[1] cont
Breakpoint hit: "thread=main", Jdb.square(), line=4 bci=4
main[1] print result
result = 4
main[1] clear Jdb:4
Removed: breakpoint Jdb:4
main[1] cont
> Sum: 14cont lets the program continue. In the second iteration of the loop square(2) is called, and the program stops again at the same breakpoint. This time print result shows 4. clear Jdb:4 removes the breakpoint; with the last cont, the program runs to the end without stopping again and prints Sum: 14.
| Command | Stopped at | i (main) | x | result | total |
|---|---|---|---|---|---|
run | square, line 4 | 1 | 1 | 1 | 0 |
cont | square, line 4 | 2 | 2 | 4 | 1 |
clear + cont | the program ends | — | — | — | 14 |
The total column in Table 7.16 is the value in main at the moment of stopping at the breakpoint. At the second stop, total is 1, because the result of the first iteration has been added and that of the second has not yet been. Had the breakpoint been set on line 3 (int result = x * x;), the locals command would not have shown result: since the line has not run yet, the variable does not exist at that moment.
7.6.7Systematic debugging
The debugger is a powerful tool, but it is not a method on its own. Setting random breakpoints and changing the code at random can take hours. Experienced programmers follow a five-step path.
- Reproduce. Find the smallest input that triggers the failure every time, for example
{-5, -2, -8}. A bug that cannot be reproduced cannot be debugged. - Write it as a test. Write a unit test that fails on this input. The red test is the proof of the bug, and it will also show that the fix worked.
- Narrow it down. Start from the first line in the stack trace. Watch the variables at breakpoints and shrink the suspicious region by halving it. The place you are looking for is the line where a value first becomes wrong.
- Form a hypothesis and test it. Propose an explanation such as "
bestis never updated because it starts at 0" and confirm it in the debugger. Changing code by guesswork creates new bugs. - Fix and run all the tests. The new test must turn green and the old ones must stay green; that is, there must be no regression. The test stays in the test suite permanently.
The idea of "halving" in the third step resembles binary search. If the result of a 200-line computation is wrong, a breakpoint is first set on the middle line, line 100. If the values are correct there, the defect is in the second half; if they are wrong, it is in the first half. At each step the region being searched is halved. 200 lines shrink to a single line in at most eight steps, since 28 = 256 ≥ 200.
Another tool that helps with narrowing is Java's assert statement. assert lets the programmer write into the code the assumption "at this point this condition is always true." If the condition is false, the program throws AssertionError, and the problem is caught where it occurs.
static double average(int[] d) {
assert d.length > 0 : "empty array";
int t = 0;
for (int v : d) {
t += v;
}
return (double) t / d.length;
}public static void main(String[] a) {
System.out.println(average(new int[] {1, 2}));
System.out.println(average(new int[0]));
}$ java As
1.5
NaN
$ java -ea As
1.5
Exception in thread "main" java.lang.AssertionError: empty array
at As.average(As.java:3)
at As.main(As.java:12)The output shows an important detail: assert statements are disabled by default. The program run with plain java As gives no warning for the empty array. The division 0 / 0 produces NaN (not a number) in double; the program silently prints a wrong value. When it is run with the -ea (enable assertions) option, the assumption is checked. The moment the program is called with an empty array, it stops at line 3 with AssertionError: empty array. For this reason, assert is turned on during development and testing and left off in the program that goes to the user. To check user input, use an exception, not assert; a disabled assert prevents nothing.
7.7Analysis tools
Unit tests and the debugger are the two tools programmers use most often, but they do not answer every question. Questions such as "Why is the program slow?", "How much of the code do my tests exercise?", and "Why is memory filling up?" need other tools. Each of the tools in this section focuses on a single question.
7.7.1The profiler
A profiler is a tool that measures where a program spends its time and memory. It shows which method was called how many times, how long it took, and how much memory it allocated.
A profiler presents the call graph, which shows who calls whom, in several forms: a flat list, a tree, or a flame graph. In a flame graph, each method is a box; the width of the box is proportional to the time spent in that method. Wide boxes stand out immediately. The technical details of the measurement vary with the compiler and the JVM version in use.
The basic rule of profiling is short: measure first, then optimize. Most of a program's time is usually spent in a small region, a hot spot. The programmer's guess often misses this spot. An optimization made by guesswork complicates the code and speeds up the wrong place.
Old JVMs had a built-in profiler that was switched on with the java -Xprof option. This option was removed in Java 10. In Java 21, the same option only produces a warning and is ignored:
OpenJDK 64-Bit Server VM warning: Ignoring option -Xprof; support was removed in 10.0Today other tools are used in Java. The JDK Flight Recorder (JFR) that ships with the JDK records events, and JDK Mission Control visualizes these recordings. To these are added the free VisualVM and the built-in profilers of IDEs. JFR records events while the program runs, slowing it down very little. The program is run with a JFR recording like this, and a summary of the recording is obtained like this:
java -XX:StartFlightRecording=filename=rec.jfr Profile
jfr summary rec.jfrThe first command runs the program and writes the events to the file rec.jfr. The second command lists the event types and counts in the recording. A detailed analysis is usually done by opening this file in JDK Mission Control.
7.7.2Measuring a hot spot
To see the value of profiling, two methods that do the same job in two different ways are compared. Both build a string by writing the numbers from 0 to n − 1 one after another.
public class Profile {
static String concatPlus(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += i; // new String each pass
}
return s;
}
static String concatBuilder(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(i);
}
return sb.toString();
}
// main: see the next box
}public static void main(String[] args) {
long t0 = System.nanoTime();
String a = concatPlus(50_000);
long t1 = System.nanoTime();
String b = concatBuilder(50_000);
long t2 = System.nanoTime();
long ms1 = (t1 - t0) / 1_000_000;
long ms2 = (t2 - t1) / 1_000_000;
System.out.println("+= : " + ms1 + " ms");
System.out.println("SB : " + ms2 + " ms");
System.out.println(a.equals(b));
}The main method measures the time of the two methods with System.nanoTime(). This method returns a timestamp in nanoseconds; the difference of two timestamps is divided by 1,000,000 to convert it to milliseconds. The last line verifies that the two strings are identical: the speed difference must not change the result. In one run the output is as follows; the numbers vary with the machine and the run:
+= : 873 ms
SB : 2 ms
true+=, about 2 milliseconds with StringBuilder.The difference is hundreds of times (Figure 7.16). While this note was being prepared, in three runs with JDK 21 the += version took 862–922 ms and the StringBuilder version 2–4 ms. The reason is that String is immutable. s += i cannot modify the old string; it creates a new String in every iteration. All the characters of the old string are copied into this new object. In iteration k, the number of characters copied is roughly proportional to k. The total work grows as 1 + 2 + … + n ≈ n²/2: O(n²). StringBuilder, on the other hand, appends to a single buffer. When the buffer fills up, it is moved to a larger one, but since the size doubles each time, the total copying stays O(n).
In this program the hot spot is obvious. In a real program, however, it is not visible at first glance: the line s += i sits in an innocent-looking loop among hundreds of lines. A profiler shows that 99% of the time is spent on this line and tells you where to make the improvement.
7.7.3Code coverage
Code coverage measures which parts of the code are executed while the tests run. The result is usually given as a ratio: the ratio of executed lines or branches to the total.
A code coverage tool reveals pieces of code that are never executed or used, and helps find untested regions. For this reason, it is an important tool for increasing the reliability of software. In Java, the most common tool is JaCoCo, which works with Maven and Gradle. The "Run with Coverage" command in IntelliJ and the EclEmma plugin in Eclipse do the same job. The result is shown by coloring the lines of code: executed lines green, never executed ones red.
| Criterion | What is counted? |
|---|---|
| Line | Lines executed at least once |
| Branch | Both the true and the false outcome of every if / loop condition |
| Method | Methods called at least once |
Of the three criteria in Table 7.17, the strictest is branch coverage. When an if line runs, line coverage counts it as "executed." Branch coverage, in contrast, wants to see the condition come out both true and false. If the condition has always been true, a defect hiding in the false branch has never been tried.
One must know the limit of coverage well: 100% coverage does not mean defect-free code. Coverage says only that a line was executed, not that its result was correct. A test that contains no assertion and merely calls the method also raises coverage. A coverage report is very valuable for the warning "this was never tried"; as for "this is correct," it says nothing.
7.7.4Code trace: code coverage
The example method returns the sign of a number as a string.
public class Sign {
public static String sign(int x) {
if (x > 0) {
return "positive";
} else if (x < 0) {
return "negative";
}
return "zero";
}
}The executable lines of the method are 3, 4, 5, 6, and 8. Lines 1, 2, and 7 are declarations or closing braces; coverage tools do not count them. There are two conditions: x > 0 and x < 0. Since each condition has two branches, 4 branches are counted in total. Two tests have been written for the method:
class SignTest {
@Test
void positive() {
assertEquals("positive", Sign.sign(5));
}
@Test
void negative() {
assertEquals("negative", Sign.sign(-3));
}
}In the call sign(5), line 3 runs and x > 0 is true; line 4 returns "positive". The test passes. Coverage: 2 of 5 lines, 1 of 4 branches. In the call sign(-3), the condition on line 3 is false (a new branch), x < 0 on line 5 is true (a new branch), and line 6 returns "negative". Both tests are green.
x < 0 have never been tried.| Test | Lines executed | Branches tried | Line coverage | Branch coverage |
|---|---|---|---|---|
| (none) | — | — | 0 / 5 | 0 / 4 |
sign(5) | 3, 4 | x > 0 true | 2 / 5 = 40% | 1 / 4 = 25% |
+ sign(-3) | 3, 4, 5, 6 | + x > 0 false, x < 0 true | 4 / 5 = 80% | 3 / 4 = 75% |
+ sign(0) | 3, 4, 5, 6, 8 | + x < 0 false | 5 / 5 = 100% | 4 / 4 = 100% |
Table 7.18 shows the missing test clearly. Despite two green tests, line 8 and the false branch of the condition x < 0 have never been tried. Only an input for which both conditions are false, that is 0, reaches this branch. The coverage report thus exposes the forgotten boundary value: sign(0). When this test is added, line and branch coverage become 100%, and the test verifies that the method returns "zero".
Even at 100% coverage, it is not coverage but assertEquals that checks correctness. Had line 8 mistakenly been return "positive";, a test that calls sign(0) without looking at the result would still bring coverage to 100%.
7.7.5Static analysis: FindBugs and SpotBugs
Static analysis is an inspection that looks for bug patterns without running the code. The word "static" says that the program is not running; tests and the debugger, in contrast, run the program and are dynamic tools.
FindBugs was a tool developed for the static analysis of Java code. Without running the program, it inspected the compiled code and looked for known bug patterns: null dereferences, wrong comparisons, resources that are never closed. FindBugs is no longer developed; its successor is SpotBugs. SpotBugs is used through Maven, Gradle, and IDE plugins. Similar tools include PMD, Checkstyle, and SonarQube.
import java.util.Scanner;
public class SpotDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String answer = sc.nextLine();
// result ignored:
answer.trim();
// String compared with ==:
if (answer == "yes") {
System.out.println("Approved");
} else {
System.out.println("Rejected");
}
}
}The program reads an answer from the user and approves if it is "yes". Even though the user types yes, the output is Rejected. The program has two defects, and the compiler stays silent about both.
| SpotBugs pattern | Warning |
|---|---|
ES_COMPARING_STRINGS_WITH_EQ | String objects are compared with ==; the correct way is equals |
RV_RETURN_VALUE_IGNORED | trim() returns a new String; the result is discarded |
The first pattern in Table 7.19 is a reminder that == checks whether two references point to the same object. nextLine() creates a new String object for the text read from the keyboard. This object is not the same object as the "yes" constant in the code; even if their contents are the same, == returns false. The correct form is "yes".equals(answer). The second pattern concerns the immutability of String. answer.trim() does not change answer; it returns a new string with the leading and trailing whitespace removed. Because the result is not assigned to a variable, the line does nothing. The correct form is answer = answer.trim();.
A test could also have found these two defects, but only if it had been written with the right input. Static analysis, on the other hand, needs no input: it warns wherever it sees the pattern. This is why it complements tests rather than replacing them. Static analysis cannot know about logic errors; a defect such as "the difference is computed instead of the sum" matches no pattern.
7.7.6The first static analyzer: the compiler
Every Java programmer already has a static analyzer at hand: javac. The compiler inspects the code without running it and reports compile errors. With the -Xlint option, it also reports constructs that are not compile errors but look suspicious.
public class Lint {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
break;
}
int x = 10 / 0;
}
}The program compiles and runs, but it contains two defects. The break has been forgotten at the end of case 1 and case 2. On line 13 there is also a division by a constant zero. When run, the output is as follows:
Tuesday
Wednesday
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Lint.main(Lint.java:13)For day = 2, execution enters at case 2. Since there is no break, control falls through to case 3, and Wednesday is printed as well. Then the division on line 13 throws ArithmeticException. Plain javac Lint.java compiles this program without any warning. When it is compiled with -Xlint:all, both defects become visible without running the program:
Lint.java:13: warning: [divzero] division by zero
int x = 10 / 0;
^
Lint.java:7: warning: [fallthrough] possible fall-through into case
case 2:
^
Lint.java:9: warning: [fallthrough] possible fall-through into case
case 3:
^
3 warningsThe [divzero] warning reports the division by a constant zero, and the two [fallthrough] warnings report that the previous case does not end with a break. The order of the warnings follows the compiler's internal phases, not the line order. There is no warning for case 1, because no case precedes it. Reading warnings is the cheapest way of finding a bug before running the program.
7.7.7Property-based testing
In unit tests, the programmer chooses the inputs. However carefully they are chosen, there may be a case that did not occur to the programmer. Property-based testing solves this problem by letting the computer choose the inputs.
Property-based testing is testing that checks, with a large number of randomly generated inputs, that a property always holds. Instead of individual examples, the programmer writes a property: "this must be true for every input." If an input that breaks the property is found, it is reported as a counterexample.
The pioneer of the method is QuickCheck. QuickCheck generates the tests automatically: it is the tool, not the programmer, that picks the inputs at random. When a counterexample is found, the tool shrinks it where possible; this way a counterexample with 2 elements is reported instead of an array of 50 elements. The first QuickCheck was written for the Haskell language. Versions exist for many languages; in Java they are jqwik and junit-quickcheck. The test below applies the same idea with plain JUnit.
class PropertyTest {
static String randomText(Random r) {
int len = r.nextInt(20); // 0..19
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append((char) ('a' + r.nextInt(26)));
}
return sb.toString();
}
@Test
void reverseTwiceGivesSame() {
Random r = new Random(42); // fixed seed
for (int k = 0; k < 1000; k++) {
String s = randomText(r);
String t = TextUtils.reverse(s);
assertEquals(s, TextUtils.reverse(t));
}
}
}The method under test is a simple helper that reverses a string:
public class TextUtils {
public static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}The property being tested is this: reversing a string twice gives the string itself. randomText produces a random string of length 0–19 made of lowercase letters. r.nextInt(26) gives a number between 0 and 25; added to 'a' and converted to char, it becomes a letter from a to z. The test generates 1000 such strings and verifies the property for each. The fixed seed (42) makes the test deterministic: the same 1000 strings are tried in every run. When the test is run, the report is a single line: 1 test, 1000 inputs, passed.
This test tries something different from hand-picked examples. Cases such as the empty string (length 0), a one-letter string, or a repeated letter arise on their own in random generation. The programmer does not have to think of them one by one.
7.7.8The property test finds the bug in the first version
The property test can also be applied to the first, faulty version of the max method. The largest element has two properties: the result is not smaller than any element of the array, and the result is an element of the array.
class PropertyTest2 {
@Test
void maxIsLargestElement() {
Random r = new Random(7);
for (int k = 0; k < 1000; k++) {
int[] arr = new int[1 + r.nextInt(5)];
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(201) - 100; // -100..100
}
int best = ArrayUtils.max(arr);
boolean found = false;
for (int x : arr) {
assertTrue(best >= x); // property 1
if (x == best) found = true;
}
assertTrue(found, // property 2
"Counterexample: " + Arrays.toString(arr));
}
}
}The test generates 1000 random arrays with seed 7. The length of each array is 1–5, and its elements are between −100 and 100: r.nextInt(201) gives 0–200, and subtracting 100 makes the range −100..100. For each array, property 1 (best >= x) is checked first, then property 2 (found). Run with the first, faulty version, the result is this:
✘ maxIsLargestElement()
Counterexample: [-60, -69, -39, -65, -13] ==> expected: <true> but was: <false>
1 test · 1 failedThe counterexample is the second random array; the first array contains a non-negative element, and the faulty version gives the right result. All the elements of the second array are negative; the faulty version returns 0. Property 1 holds even in the faulty version: 0 is greater than all the negative numbers. Property 2, however, catches the bug: 0 is not in the array. The message, which is the second parameter of assertTrue, writes the counterexample into the report.
When the same test is run with the corrected version, all 1000 inputs pass. The lesson here is important: properties must be written completely. Had only property 1 been written, the test would have approved the faulty code too. A weak property gives a false sense of confidence.
Suppose the property "in the result array, no element is greater than the next one" is written for a sorting method. Is this property enough on its own?
It is not enough. A method that ignores its input and always returns an empty array also satisfies this property. So does a method that returns an array of all zeros. Both produce a sorted array, but it has nothing to do with the input.
The missing property is this: the result must be a permutation of the input; the same elements, the same number of times. Together, the two properties define the notion of "sorting" completely.
7.7.9Selenium
Selenium is a framework used to test web applications. It makes browser-based tests easier: it opens a real browser from a program, clicks a link, types into a form, presses a button, and verifies that the expected text appears on the page. It is used with languages such as Java, Python, C#, and JavaScript. In Java it is usually called from inside a JUnit test.
Figure 7.19 shows the path the commands follow. The test code uses a common interface called WebDriver. Each browser has its own driver (ChromeDriver for Chrome, GeckoDriver for Firefox). The same test code can be run in different browsers by swapping the driver. A typical scenario goes like this: the login page is opened, a username and password are typed, the "Log in" button is pressed, and one checks whether the text "Welcome" appears in the title.
Selenium tests check the whole that the user sees; they are at the level of system and acceptance tests. This power has a price. They are much slower than unit tests: even opening a browser takes seconds. They are also brittle: even a change in the name of a button can break the test. For this reason, their number is kept small; they stand at the top of the test pyramid.
7.7.10Memory leaks
In Java, memory is managed automatically thanks to the garbage collector. The programmer creates objects with new but never explicitly deletes them. Even so, Java programs can leak memory too.
The garbage collector (GC) is the JVM component that reclaims the memory of objects that no reference points to. A memory leak, on the other hand, is memory that is not freed because a reference to objects that are no longer needed still remains.
The key concept behind this definition is reachability. The garbage collector removes only unreachable objects. If a chain of references from anywhere in the program, for example from a static field, reaches an object, that object is not removed even if it is unnecessary for the program.
import java.util.ArrayList;
import java.util.List;
public class Leak {
static List<byte[]> cache = new ArrayList<>();
static void handle(int id) {
byte[] data = new byte[1024 * 1024]; // 1 MB
cache.add(data); // never removed!
}
public static void main(String[] args) {
for (int i = 1; ; i++) {
handle(i);
if (i % 20 == 0) {
System.out.println(i + " requests handled");
}
}
}
}The program handles requests in an infinite loop. Each request creates a 1 MB array and adds it to a static list. The list is never cleared.
static cache list holds the 1 MB arrays added on each request. All of the arrays are still reachable; the garbage collector cannot free them.When the program is run with the command java -Xmx256m Leak, the output is as follows; the lines in between have been abbreviated:
20 requests handled
…
120 requests handled
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Leak.handle(Leak.java:8)
at Leak.main(Leak.java:14)The -Xmx256m option limits the heap to at most 256 MB. After handling 120 requests, the program crashes after a while with OutOfMemoryError: Java heap space. The stack trace points to the right place of the problem: new byte[1024 * 1024] on line 8. But the real defect is not on this line. Memory runs out on that line because none of the previous arrays has been released. The defect is cache.add(data) on line 9: the data that is added is never removed again.
It may seem surprising that only about 120 arrays of 1 MB fit in a 256 MB heap. The reason is that G1, the JVM's default garbage collector, divides memory into regions. At this heap size, regions are 1 MB. A 1 MB array, together with its object header, does not fit in one region and occupies two. This is why the heap runs out when it is about half full. The exact number varies with the JVM and the settings.
7.7.11Eclipse Memory Analyzer and VisualVM
The way to find a leak is to look at the heap: which objects exist, how much space do they take, and who is holding them? Eclipse Memory Analyzer (MAT) answers these questions. It analyzes the Java heap to find memory leaks and helps with memory optimization.
The input of MAT is a heap dump (an .hprof file): a snapshot of all the objects at a given moment. A dump is taken in two ways:
// on OutOfMemoryError
java -XX:+HeapDumpOnOutOfMemoryError Leak
// from a running program
jps
jcmd <pid> GC.heap_dump heap.hprofThe first way is the -XX:+HeapDumpOnOutOfMemoryError option. A JVM started with this option dumps the heap to a file by itself at the moment memory runs out. The second way is to take a dump from a running program. jps lists the running JVMs and their process IDs (pid). jcmd <pid> GC.heap_dump heap.hprof writes the heap of that JVM to a file.
The three most important reports of MAT are these. Leak Suspects automatically finds the objects that hold a large part of the heap. The Dominator Tree shows which object holds the most memory; all the objects that would be freed together with an object if it were removed are listed under it. The Histogram gives the number of objects per class and the space they occupy.
In the Leak example, the Leak Suspects report shows that almost the whole heap is held by the Leak.cache list and the byte[] arrays inside it. The fix is one of two ways: data that is finished with is removed from the list, or a size-limited cache is used. A bounded cache discards its oldest element when it fills up, and memory use stays constant.
VisualVM watches a running program live. It visualizes memory consumption, thread usage, CPU load, and more. It connects to running JVMs, takes profiles, and takes heap and thread dumps. VisualVM is free and open source (visualvm.github.io); it used to ship with the JDK under the name jvisualvm. Tools that give similar information on the command line are jps, jstat, jcmd, and jconsole.
Figure 7.21 shows two typical views of the heap graph in VisualVM. In a healthy program, memory use rises, garbage collection kicks in, and the use falls back to the same level; the graph looks like a sawtooth. With a leak there is also a sawtooth, but the trough after each garbage collection is higher than the previous one. If the troughs keep rising, objects are not being released. This picture is the first sign of a leak. Then a heap dump is taken and MAT is used to examine who is holding what.
7.7.12Which tool for which question?
Each of the tools described in this note answers a single question. Choosing the right tool starts with putting the question correctly. Table 7.20 matches questions with tools.
| Question | Technique / tool |
|---|---|
| Does this method give the correct result? | Unit test: JUnit, @Test, assertEquals, assertThrows |
| Do the parts work together, as a whole system, and from the user's point of view? | Module, sub-system, system, acceptance (alpha / beta) testing; Selenium for the web |
| Did a change break something old? | Regression testing: all automated tests run on every change (CI) |
| Which inputs should be chosen? | Boundary values, equivalence classes, @ParameterizedTest |
| Is it correct on the inputs that were not chosen? | Property-based testing (QuickCheck, jqwik) |
| How much of the code do the tests execute? | Code coverage: JaCoCo, EclEmma |
| Is there a bug in the code that can be seen without running it? | Static analysis: javac -Xlint, SpotBugs (FindBugs) |
| Why does it work incorrectly? | Debugger: breakpoint, Step Into / Over / Out, watch; jdb |
| Where is the time being spent? | Profiler: JFR, VisualVM |
| Why is memory filling up? | Watching with VisualVM, examining the heap dump with Eclipse Memory Analyzer |
The tools in the table are not rivals but links in a chain. Regression testing reports a failure. The debugger finds the defect. After the fix, a unit test keeps the defect from coming back. The coverage report shows which tests are missing, and static analysis shows patterns that tests may miss. The profiler and the memory tools, in turn, explain why a correctly working program is slow or greedy. Testable code is usually well-designed code. Taking dependencies from outside, like the Random in the die example, makes both testing and design easier.
7.8Solved problems
The problems in this section combine the topics covered in the note. The solution of each problem is given with its intermediate steps; the JUnit results and messages have been verified by running them with JUnit 5.11.
Which test passes, and which fails?
class QuizTest {
@Test void a() { assertEquals(7, 3 + 4); }
@Test void b() { assertEquals(0.3, 0.1 + 0.2); }
@Test void c() { assertTrue("Java".length() == 4); }
@Test void d() { assertThrows(ArithmeticException.class,
() -> System.out.println(10 / 2)); }
}(a) 3 + 4 = 7; expected 7. Passes.
(b) 0.1 + 0.2 is 0.30000000000000004 in binary representation. No tolerance is given, so the comparison is exact. Fails: expected: <0.3> but was: <0.30000000000000004>.
(c) "Java".length() is 4, and the condition is true. Passes.
(d) 10 / 2 = 5; the division is fine and 5 is printed on the screen. No ArithmeticException is thrown. Fails: Expected java.lang.ArithmeticException to be thrown, but nothing was thrown.
Branch coverage in an absolute-value method. For the method below, what is the minimum number of tests needed for 100% branch coverage?
public class Abs {
static int abs(int x) {
if (x < 0) {
return -x;
}
return x;
}
}The method has a single condition (x < 0) and therefore two branches. The true branch needs a negative input (e.g. −3 → 3), and the false branch needs a zero or positive input (e.g. 5 → 5). At least 2 tests are enough. It would be good to add −1 and 0 as boundaries as well; these two values enclose the threshold from both sides. If the condition had mistakenly been written as x < -1, −1 would return −1; the tests for −3 and 5 cannot see this, and only the −1 test catches it.
What is the problem with this test class?
class CounterTest {
static int count = 0;
@Test void increment() {
count++;
assertEquals(1, count);
}
@Test void incrementTwice() {
count += 2;
assertEquals(2, count);
}
}The count field is static; it belongs to the class, and the test objects of the two tests share the same field. The result depends on the test order. In this class JUnit runs increment first: count becomes 1 and the test passes. Then incrementTwice runs: count goes from 1 to 3. Fails: expected: <2> but was: <3>. If the order were reversed, this time increment would fail (expected: <1> but was: <3>).
The fix is one of two ways. Remove the word static; since JUnit creates a new object for every test, every test starts from 0. Or reset the field in a @BeforeEach method.
Two Step Overs. In the StepDemo program, with the debugger stopped on the line int s = sumSquares(3, 4); (13), if two Step Overs are made in a row, which line do we reach, what is on the screen, and what is s?
The first Step Over runs sumSquares without entering it and completes the assignment: s = 25. The program is on line 14, at println; the screen is still empty.
The second Step Over runs println. s = 25 is printed on the screen, and the program reaches the closing line of main (15). s is 25.
Which tool? Which technique or tool should be used in each case?
(a) The program crashes with OutOfMemoryError after 10 minutes. The heap graph is watched with VisualVM; if the troughs rise, there is a leak. The heap dump (-XX:+HeapDumpOnOutOfMemoryError) is examined with Eclipse Memory Analyzer.
(b) Report generation takes 30 seconds; which method is slow? A profiler: JDK Flight Recorder or VisualVM.
(c) Did the newly added discount code break the old invoice calculation? Regression testing: all the automated tests are rerun, preferably on every change with CI.
(d) Does the registration form on the website work in all browsers? Browser-based tests with Selenium, using different browser drivers.
(e) Are there forgotten breaks in a switch? Static analysis: javac -Xlint:all (the [fallthrough] warning) or SpotBugs.
(f) A loop produces a wrong value in the 10,000th iteration; what are the variables at that moment? A conditional breakpoint in the debugger: i == 9999. Since the loop counter starts at 0, the 10,000th iteration has i = 9999.
Boundaries of a primality check. How are the boundary values 0, 1, 2, 3, 4, 97, and 100 tested with @ParameterizedTest for static boolean isPrime(int n)?
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
@ParameterizedTest
@CsvSource({"0, false", "1, false", "2, true", "3, true",
"4, false", "97, true", "100, false"})
void primeBoundaries(int n, boolean expected) {
assertEquals(expected, isPrime(n));
}All seven calls pass. 0 and 1 are not prime; the first line of the method separates these two cases. 2 is the smallest prime and never enters the loop, because 2 × 2 > 2. 4 is the smallest composite number; the loop finds a divisor at d = 2. 0, 1, and 2 are the boundaries where most mistakes are made: if n < 1 is written instead of n < 2, 1 is taken to be prime. The d * d <= n in the loop condition is a boundary too: had < been written, 4 would be taken to be prime, because for d = 2, 4 < 4 is false and the loop would never run.
Testing a rectangle class. Write a JUnit 5 test class for a Rectangle class (width, height, area(), perimeter()); a negative side must throw IllegalArgumentException.
class RectangleTest {
@Test
void areaCorrect() {
assertEquals(12.0, new Rectangle(3, 4).area(), 1e-9);
}
@Test
void perimeterCorrect() {
assertEquals(14.0, new Rectangle(3, 4).perimeter(), 1e-9);
}
@Test
void negativeSideRejected() {
assertThrows(IllegalArgumentException.class,
() -> new Rectangle(-1, 2));
}
}A 3 × 4 rectangle has area 12 and perimeter 2 × (3 + 4) = 14. Since the sides are double, a tolerance is given in the assertions. A rectangle with a zero side should also be tried as a boundary: its area is 0, and it must not throw an exception.
TDD for a transfer method. A method transfer(BankAccount target, double amount) is to be added to BankAccount. Which tests are written before any code?
(1) Successful transfer: both balances change; the sender's balance decreases and the receiver's increases. (2) Insufficient funds: an exception is thrown and neither balance changes. (3) Negative amount: rejected. (4) Transfer to oneself: the agreed behavior (rejection or a no-op) is tested.
The second test is especially important. If the transfer first withdraws from the sender and then deposits to the receiver, and the deposit step throws an exception, the money can be lost in thin air. Each test is first red, and then turns green with the code that is written.
Integer division in an average. A method that computes the average of an array returns 1.0 instead of 1.5 for {1, 2}. How is the defect found with the debugger?
First a failing test is written: for {1, 2}, expected 1.5. A breakpoint is set on the return line. The variable total and the division expression are watched: total is 3, which is correct. total / arr.length, however, gives 1: since two ints are divided, this is an integer division (3 / 2 = 1). The result is converted to double only after the division and becomes 1.0. The fix is (double) total / arr.length: the conversion happens before the division, the division becomes floating-point, and gives 1.5. Then all the tests are run.
7.9Common mistakes
| Mistake | Consequence | The right way |
|---|---|---|
Writing expected and actual the wrong way around: assertEquals(calc.add(2, 3), 5) | It works, but when it fails the message reads backwards: expected shows the actual result | Expected first, then actual |
Forgetting the tolerance for floating-point numbers: assertEquals(0.3, 0.1 + 0.2) | expected: <0.3> but was: <0.30000000000000004> | assertEquals(0.3, 0.1 + 0.2, 1e-9) |
Missing import static | Compile error: cannot find symbol, method assertEquals(int,int) | import static org.junit.jupiter.api.Assertions.*; |
| Mixing JUnit 4 and 5 | org.junit.Test and org.junit.jupiter.api.Test are different; a wrong import can make the tests not run at all | In a JUnit 5 project, only org.junit.jupiter.api |
A @BeforeAll method that is not static | JUnit does not run the tests in the class: @BeforeAll method '…' must be static … | static void start() |
| Dependencies between tests | When the order changes, the tests fail randomly | Each test sets up its own data |
| A test without an assertion | The test is always ✔ and proves nothing; it still raises coverage | At least one assertion in every test |
| Testing only the "happy path" | Boundaries (0, empty array, negative), invalid inputs, and exceptions are forgotten; the bugs are exactly there | Normal case + boundary + invalid input |
Comparing arrays with assertEquals | Fails even when the contents are the same; the references are compared | assertArrayEquals |
An unseeded Random or LocalDate.now() | A flaky test: sometimes passes, sometimes fails | Supply the dependency from outside, use a fixed seed |
Most of the mistakes in Table 7.21 get past the compiler. A reversed assertEquals, a test without an assertion, or two tests that depend on each other produce no warning at all. For this reason, test code must be read as carefully as production code. A simple way to see that a test itself is correct is to deliberately make it go red once: the expected value is written wrongly on purpose, and one checks that the test really fails. A test that never fails may not be testing anything.
7.10Summary
- Testing systematically checks whether a program shows the expected behavior. A test can show the presence of bugs but not their absence; well-chosen tests raise confidence.
- An error is the programmer's mistake, a defect is its counterpart in the code, and a failure is the wrong behavior seen at run time. Testing exposes the failure, and debugging finds the defect.
- The test levels are unit, module, sub-system, system, and acceptance testing. A bug caught low is cheap; one caught high is expensive. Black-box testing starts from the requirements, white-box testing from the code.
- In JUnit 5, test methods are marked with
@Test; the result is checked with assertions such asassertEquals(expected, actual). Use a tolerance for floating-point numbers andassertArrayEqualsfor arrays. - A good test follows the arrange, act, assert (AAA) pattern and checks a single behavior. The test name describes the behavior.
- JUnit creates a new test object for every test.
@BeforeEachruns before every test and@AfterEachafter every test (even if the test fails).@BeforeAlland@AfterAllrun once and must bestatic. assertThrowsverifies that the code throws an exception of the expected type (or a subtype) and returns the exception object.- Bugs occur most often at the boundaries. Boundary value analysis chooses both ends of each range and the first values of the invalid region; a single representative of an equivalence class is enough.
@ParameterizedTestand@CsvSourcerun the same test with many data rows. - A good unit test is fast, independent, repeatable, self-validating, and timely (FIRST). External dependencies are replaced with test doubles.
- Regression testing means rerunning all the tests after every change. Tests must be deterministic; randomness is controlled with a fixed seed and dependency injection. CI systems run the tests on every push.
- In TDD, a failing test is written first (red), then the simplest code that makes it pass (green), and then the code is cleaned up (refactoring).
- The debugger stops the program at a breakpoint, before the line runs. Step Into enters a method, Step Over passes a call in a single step, and Step Out finishes the current method. Conditional and exception breakpoints catch the moment you are looking for.
jdbdoes the same job from the command line. - Systematic debugging: reproduce, write a failing test, narrow down, form and test a hypothesis, fix and run all the tests.
assertassumptions are checked when-eais on. - A profiler (JFR, VisualVM) measures the hot spot where time is spent: measure first, then optimize. Code coverage (JaCoCo) shows lines and branches that never run; 100% coverage does not mean defect-free code.
- Static analysis (
javac -Xlint, SpotBugs) finds suspicious patterns without running the code. Property-based testing checks a property with random inputs; if the property is weak, it also approves faulty code. - Selenium tests a web application in a real browser. A memory leak is a reference that remains to objects that are no longer needed; it shows up as rising troughs in VisualVM, and the heap dump is examined with Eclipse Memory Analyzer.
7.11Key terms
- testing
- error / defect / failure
- debugging
- debugger
- unit test
- module, sub-system, system, acceptance testing
- black-box / white-box testing
- framework
- annotation
- assertion
- lambda expression
- test lifecycle
- arrange, act, assert
- boundary value analysis
- equivalence class
- parameterized test
- integration test
- test double
- regression test
- flaky test
- seed
- dependency injection
- continuous integration
- test-driven development
- breakpoint
- call stack
- stack frame
- profiler
- hot spot
- code coverage
- static analysis
- property-based testing
- counterexample
- garbage collector
- memory leak
- heap (memory)
- heap dump
7.12Test Yourself
In the questions, the classes used in the note (BankAccount, StepDemo, Jdb, Die) apply exactly as written.
Does
assertEquals(0.1 * 3, 0.3)pass? If it fails, what is the message, and what is misleading about it?Answer
It fails:
expected: <0.30000000000000004> but was: <0.3>. There are two problems. There is no tolerance: 0.1 × 3 is not exactly 0.3 in binary. The parameters are also in the wrong order: the computed value has taken the place of "expected," and the constant 0.3 looks like the "actual" value. The correct form isassertEquals(0.3, 0.1 * 3, 1e-9).A test class has three ordinary
@Testmethods and a@ParameterizedTestwhose@CsvSourcehas three rows. How many times does the@BeforeEachmethod run?Answer
6 times. Each row of the parameterized test is a separate test invocation, and
@BeforeEachruns before every invocation: 3 + 3 = 6.For an account with a balance of 100, does
assertThrows(IllegalStateException.class, () -> acct.deposit(-10))pass?Answer
It fails.
deposit(-10)throws an exception, but its type isIllegalArgumentException; this class is not a subclass ofIllegalStateException. The message:Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.IllegalArgumentException>.In the
Jdbprogram, a breakpoint is set on line 3 (int result = x * x;) withstop at Jdb:3. How many times does the program stop? What doeslocalsshow at the first stop?Answer
It stops three times:
squareis called three times in the loop, andxis 1, 2, 3 in turn. At the first stop,localsshows only the method argumentx = 1; the list of local variables is empty. Since line 3 has not run yet,resultdoes not exist at that moment.The method
static String kind(int n)consists of three executable lines:if (n % 2 == 0),return "even";, andreturn "odd";. If there is only a test forkind(4), what are the line and branch coverage?Answer
4 is even; the
ifline andreturn "even";run. Line coverage is 2 / 3 ≈ 67%. Of the two branches of the single condition, only the true branch has been tried: branch coverage is 1 / 2 = 50%. A second test with an odd input, for examplekind(3), brings both to 100%.In the
StepDemoprogram, the debugger is stopped insidesquarewithx = 3. First Step Out is made, then Step Over. Which line is the program on, and what issq1?Answer
Step Out finishes
square(3)and returns to line 7,int sq1 = square(a);; the return value is 9, but the assignment has not completed yet. Step Over completes the assignment and moves to line 8.sq1 = 9.A store gives a 10% discount to anyone who buys 6 or more items; the number of items cannot be negative. Which inputs does boundary value analysis choose?
Answer
Equivalence classes: invalid (< 0), no discount (0–5), discount (≥ 6). Boundaries: −1 (the first value of the invalid region), 0 (the start of the valid region), and 5 and 6 (the pair that encloses the discount threshold from both sides). If the threshold had mistakenly been written as
qty > 6instead ofqty >= 6, only 6 would catch this defect.Suppose
TextUtils.reversehad mistakenly been written asreturn s;: it does not change the string at all. Does the property test "reversing twice does not change the string" catch this defect? How can it be strengthened?Answer
It does not:
reverse(reverse(s))is stills, and all 1000 inputs pass. The property is correct, but on its own it is weak. To strengthen it, add a second property: the first character of the result is the last character of the input. Or verify a few known examples:assertEquals("cba", TextUtils.reverse("abc")).
7.13Further reading
- JUnit Team, JUnit 5 User Guide (junit.org/junit5/docs/current/user-guide), the sections "Writing Tests", "Assertions", and "Parameterized Tests": the official and up-to-date account of annotations, assertions, and parameter sources.
- K. Beck, Test-Driven Development: By Example: applies the red-green-refactor cycle step by step on a currency example; it is the book of the person who established the method.
- C. S. Horstmann, Core Java, Volume I: Fundamentals (12th ed.), Chapter 7, "Exceptions, Assertions, and Logging": covers the
assertstatement, logging, and debugging tips with Java-specific details. - Oracle, Programming With Assertions: a short official document that explains when to use
assertand when not to.
7.14References
- JUnit Team, JUnit 5 User Guide, junit.org/junit5/docs/current/user-guide (Writing Tests, Assertions, Parameterized Tests).
- Oracle, The Java Tutorials and JDK 21 Tool Specifications:
javac(-Xlint),jdb,jcmd,jfr. - Oracle, Programming With Assertions (Java SE documentation).
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (14.10 The assert Statement).
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson.
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 7: Exceptions, Assertions, and Logging).
- K. Beck, Test-Driven Development: By Example, Addison-Wesley.
- Tool documentation: SpotBugs (spotbugs.github.io), JaCoCo (jacoco.org), Selenium (selenium.dev), Eclipse Memory Analyzer (eclipse.dev/mat), VisualVM (visualvm.github.io), jqwik (jqwik.net).
Related pages: Chapter 7 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.