Part 10 / Stage 2
Testing and code quality
Goal: Write real, automated JUnit 5 tests for code you already know how to write (a discount calculator, a bank account), without a build tool — and pick up the code-quality habits (naming, Javadoc, logging) that make those tests, and the code they test, worth reading later. Time: ~5 hours · Level: comfortable with methods (Part 5), exceptions (Part 6) and plain classes
What you will learn
- Why an automated test beats "I ran it and it looked fine"
- Running JUnit 5 with no Maven: the
junit-platform-console-standalonejar on a manual classpath @Test, assertions, and reading a JUnit report — green and red- Naming a test so its name is the first line of documentation, plus
@DisplayName assertEquals,assertTrue/assertFalse,assertThrows,assertAll, and giving every assertion a message worth reading on failure@BeforeEach/@AfterEach/@BeforeAll/@AfterAll: giving every test a clean, independent starting point@ParameterizedTestwith@ValueSource,@CsvSource: one test body, many inputs- Writing your own test double by hand — a fake, not a mock, and no library for it
- What to test (behaviour, edges, errors) and what not to bother testing
- Naming/style conventions, a real Javadoc comment, and basic logging with
java.util.logging - Setting a breakpoint and stepping through code in an IDE
- Just enough Git to save this part's work and push it to GitHub
⚠️ No Maven yet. Stage 3 Part 15 introduces Maven, and from then on JUnit arrives through a
pom.xmllike any other dependency. Until then, this part manages JUnit the same honest, manual way Part 7 managed multiple files and Part 11 will manage the SQLite driver: one jar, downloaded once, named on the command line every time. You are not missing a step — this is the deliberate "no build tool before Part 15" rule this course follows (see the rootDESIGN-NOTES.md, decision 8).
Topics in this part
Practice
Try each one yourself first. Then check the solution. Every exercise compiles and runs against the pinned junit-platform-console-standalone-1.14.5.jar from examples/lib/ — copy it (or symlink it) into wherever you keep your own practice files, the same way the README's examples/bank-and-discount/ does with ../lib/....
Exercise 1: Your first test
Scenario: A weather app for Pune converts temperatures from Celsius (what its sensors report) to Fahrenheit (what some of its older users expect).
What to do: You are given Temperature.java:
public class Temperature {
public static double celsiusToFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32;
}
}
Write TemperatureTest.java yourself, with two @Test methods: one checking celsiusToFahrenheit(0) is 32.0 (freezing point), and one checking celsiusToFahrenheit(37) is 98.6 (human body temperature) — both within a 0.01 delta. Name both methods using this part's methodUnderTest_condition_expectedResult convention.
Sample output:
$ javac -cp junit-platform-console-standalone-1.14.5.jar Temperature.java TemperatureTest.java
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --scan-class-path --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ TemperatureTest ✔
│ ├─ celsiusToFahrenheit_bodyTemperature_returns98Point6() ✔
│ └─ celsiusToFahrenheit_freezingPoint_returns32() ✔
└─ JUnit Vintage ✔
[ 2 tests found ]
[ 2 tests successful ]
[ 0 tests failed ]
💡 Hint: 37 * 9.0 / 5.0 + 32 is 98.6, but floating-point arithmetic rarely lands on that exact bit pattern — assertEquals(98.6, result, 0.01), never assertEquals(98.6, result) with no third argument, for a double.
Exercise 2: Fix the broken test
Scenario: A teammate wrote a test file for Temperature (Exercise 1) and ran out of time before their coffee break.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class WeatherConversionTest {
@Test
void celsiusToFahrenheit_freezingPoint_returns32() {
double result = Temperature.celsiusToFahrenheit(0)
assertEquals(100.4, result, 0.01);
}
void celsiusToFahrenheit_bodyTemperature_returns98Point6() {
double result = Temperature.celsiusToFahrenheit(37);
assertEquals(98.6, result, 0.01);
}
}
What to do: Fix every problem so both tests compile, both run, and both pass. There are three separate problems, each at a different stage: one stops it from compiling at all, one stops a test from ever being discovered, and one makes a discovered test fail for a wrong reason.
Sample output: (the first problem, before anything else is fixed)
$ javac -cp junit-platform-console-standalone-1.14.5.jar Temperature.java WeatherConversionTest.java
WeatherConversionTest.java:8: error: ';' expected
double result = Temperature.celsiusToFahrenheit(0)
^
1 error
Sample output: (after fixing only the semicolon — notice only 1 test is found, not 2)
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --scan-class-path --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ WeatherConversionTest ✔
│ └─ celsiusToFahrenheit_freezingPoint_returns32() ✘ expected: <100.4> but was: <32.0>
└─ JUnit Vintage ✔
[ 1 tests found ]
[ 0 tests successful ]
[ 1 tests failed ]
Sample output: (fully fixed)
[ 2 tests found ]
[ 2 tests successful ]
[ 0 tests failed ]
💡 Hint: The missing ; is the compile error. The second method has no @Test — it compiles fine, but the launcher never sees it, which is why only 1 test was found instead of 2 even after the semicolon is fixed. 100.4 is simply the wrong expected value for celsiusToFahrenheit(0) — the real freezing point in Fahrenheit is 32.0.
Exercise 3: A MetroCard, tested from a clean start every time
Scenario: Pune Metro's smart card: top up (recharge), pay a fare (debit), never go below a minimum fare or above the available balance.
What to do: You are given MetroCard.java and InsufficientBalanceException.java:
public class MetroCard {
public static final double MINIMUM_FARE = 10.0;
private double balance;
public MetroCard(double openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("opening balance cannot be negative: " + openingBalance);
}
this.balance = openingBalance;
}
public void recharge(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("recharge amount must be positive: " + amount);
}
balance += amount;
}
public void debit(double fare) {
if (fare < MINIMUM_FARE) {
throw new IllegalArgumentException("fare cannot be below the minimum fare of " + MINIMUM_FARE);
}
if (fare > balance) {
throw new InsufficientBalanceException("cannot debit " + fare + ", balance is only " + balance);
}
balance -= fare;
}
public double getBalance() {
return balance;
}
}
Write MetroCardTest.java with a @BeforeEach method that creates a fresh new MetroCard(100.0) before every test, so no test can see another test's recharge or debit. Then write five tests: a successful recharge, a recharge of zero or a negative amount throwing IllegalArgumentException, a successful debit, a debit below the minimum fare throwing IllegalArgumentException, and a debit above the balance throwing InsufficientBalanceException — check that last exception's message too. Give at least one test a @DisplayName.
Sample output:
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class MetroCardTest --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ MetroCardTest ✔
│ ├─ recharge_zeroOrNegative_throwsIllegalArgumentException() ✔
│ ├─ debit_belowMinimumFare_throwsIllegalArgumentException() ✔
│ ├─ debit_validFare_decreasesBalance() ✔
│ ├─ recharge adds to the balance ✔
│ └─ debit_moreThanBalance_throwsInsufficientBalanceExceptionWithClearMessage() ✔
└─ JUnit Vintage ✔
[ 5 tests found ]
[ 5 tests successful ]
[ 0 tests failed ]
💡 Hint: assertThrows returns the exception it caught — keep that return value in a variable and call .getMessage() on it to check the exact text, the same way the lesson's BankAccountTest checks InsufficientFundsException's message.
Exercise 4: Postage, by weight, with one test body
Scenario: A courier app in Pune prices a parcel by weight band: up to 1 kg costs ₹40, up to 5 kg costs ₹80, anything heavier costs ₹150; zero or negative weight makes no sense and must be rejected.
What to do: Write PostageCalculator.costFor(double weightInKg) yourself (the three bands above, throwing IllegalArgumentException for weight ≤ 0), then write PostageCalculatorTest.java with:
- one
@ParameterizedTest+@CsvSourcecovering at least one weight from each band (try0.5,1.0,1.5,5.0,5.5), - one
@ParameterizedTest+@ValueSourcecovering at least three non-positive weights, all expected to throw.
Sample output:
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class PostageCalculatorTest --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ PostageCalculatorTest ✔
│ ├─ costFor_nonPositiveWeight_throwsForEveryValue(double) ✔
│ │ ├─ weight 0.0 is invalid ✔
│ │ ├─ weight -1.0 is invalid ✔
│ │ └─ weight -10.5 is invalid ✔
│ └─ costFor_variousWeights_matchExpected(double, double) ✔
│ ├─ 0.5 kg costs 40.0 ✔
│ ├─ 1.0 kg costs 40.0 ✔
│ ├─ 1.5 kg costs 80.0 ✔
│ ├─ 5.0 kg costs 80.0 ✔
│ └─ 5.5 kg costs 150.0 ✔
└─ JUnit Vintage ✔
[ 8 tests found ]
[ 8 tests successful ]
[ 0 tests failed ]
💡 Hint: @CsvSource rows are matched to parameters in order — "1.5, 80.0" becomes (1.5, 80.0) for (double weightInKg, double expected). weightInKg <= 1 must come before weightInKg <= 5 in your if chain, or every weight will match the first, widest check.
Exercise 5: What to test — the boundaries nobody checked
Scenario: Exercise 3's MetroCardTest tests a normal debit and two error cases, but never the exact edges of debit's own rule: "fare cannot be below the minimum fare" and "fare cannot be above the balance."
What to do: Using the same MetroCard from Exercise 3, write MetroCardBoundaryTest.java with exactly two tests: a debit of exactly MetroCard.MINIMUM_FARE (which should succeed, not throw — the rule is "below", not "below or equal to"), and a debit of exactly the full balance (which should succeed and leave the balance at 0.0, not throw InsufficientBalanceException).
Sample output:
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class MetroCardBoundaryTest --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ MetroCardBoundaryTest ✔
│ ├─ debit_exactlyMinimumFare_succeeds() ✔
│ └─ debit_exactlyFullBalance_leavesZeroBalance() ✔
└─ JUnit Vintage ✔
[ 2 tests found ]
[ 2 tests successful ]
[ 0 tests failed ]
💡 Hint: Read debit's two if conditions literally: fare < MINIMUM_FARE and fare > balance. A fare equal to either boundary fails both conditions, so it must be allowed — if your test expects an exception here and gets none, re-read the </> in the production code before touching the test.
Exercise 6: A test double for an SMS confirmation
Scenario: MetroCard's recharge should send a confirmation SMS, but a test must never dial out to a real SMS gateway.
What to do: Write an SmsGateway interface with one method, send(String phoneNumber, String message). Write MetroCardWithSms (a copy of MetroCard with a phoneNumber field and an SmsGateway passed into its constructor) whose recharge also calls smsGateway.send(...) with a message containing the new balance. Write FakeSmsGateway, a hand-rolled test double that records every call in a List<String> instead of sending anything. Then write MetroCardWithSmsTest.java with two tests: recharging sends exactly one SMS whose text contains the new balance, and that SMS goes to the card's own phone number.
Sample output:
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class MetroCardWithSmsTest --details=tree --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ MetroCardWithSmsTest ✔
│ ├─ recharge_success_sendsSmsToTheCardsOwnPhoneNumber() ✔
│ └─ recharge_success_sendsExactlyOneConfirmationSms() ✔
└─ JUnit Vintage ✔
[ 2 tests found ]
[ 2 tests successful ]
[ 0 tests failed ]
💡 Hint: This is Section 9's AlertService/FakeAlertService pattern, renamed: the one thing that makes any of it testable is passing SmsGateway into MetroCardWithSms's constructor instead of creating a real one inside it.
Exercise 7: Reproduce and fix a real test failure
Scenario: The README showed a red test happening to someone else (BrokenTest.java). Now make one happen to you, on purpose, using MetroCard from Exercise 3, and write down exactly what you saw.
What to do:
- Write
RechargeMathTest.javawith a@BeforeEachcreatingnew MetroCard(100.0), and one test that callscard.recharge(25.0)then asserts the new balance is135.0(a deliberately wrong number). - Compile and run it, and copy the exact failing line (
expected: <...> but was: <...>) and the exit code into a comment at the top of your file. - Fix the expected value to the real answer, rerun, and copy the passing line into the same comment.
Sample output: (the broken run)
$ javac -cp .:junit-platform-console-standalone-1.14.5.jar RechargeMathTest.java
$ java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class RechargeMathTest --details=tree --disable-ansi-colors
│ └─ recharge_twentyFive_balanceUpdatesCorrectly() ✘ expected: <135.0> but was: <125.0>
[ 1 tests failed ]
$ echo "EXIT:$?"
EXIT:1
Sample output: (fixed)
│ └─ recharge_twentyFive_balanceUpdatesCorrectly() ✔
[ 1 tests successful ]
💡 Hint: 100.0 + 25.0 is 125.0 — the bug here is entirely in the test's expected value, not in MetroCard.recharge. The exit code (1 for the broken run, 0 once fixed) is exactly what a CI pipeline checks; everything else in the transcript is there for a human to read.
📁 About the solution filenames: every solution file in
solutions/is named after the real class it defines —TemperatureTest.javaholdsclass TemperatureTest, and so on — because for a JUnit file the name is part of what is being tested (the console launcher's default class-name filter only picks up names ending inTest/Tests, as Exercise 2 and this part's README both show). Exercise 2's fixed file is namedWeatherConversionTest.java, notTemperatureTest.java, purely so both exercises' solutions can sit in the same folder without one overwriting the other — in your own practice folder, reusing the same name for both is fine.
👉 Solutions
Show the solutions for Part 10 (14 files)
solutions/FakeSmsGateway.java
import java.util.ArrayList;
import java.util.List;
public class FakeSmsGateway implements SmsGateway {
private final List<String> messagesSent = new ArrayList<>();
@Override
public void send(String phoneNumber, String message) {
messagesSent.add(phoneNumber + ":" + message);
}
public List<String> messagesSent() {
return messagesSent;
}
}
solutions/InsufficientBalanceException.java
public class InsufficientBalanceException extends RuntimeException {
public InsufficientBalanceException(String message) {
super(message);
}
}
solutions/MetroCard.java
public class MetroCard {
public static final double MINIMUM_FARE = 10.0;
private double balance;
public MetroCard(double openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("opening balance cannot be negative: " + openingBalance);
}
this.balance = openingBalance;
}
public void recharge(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("recharge amount must be positive: " + amount);
}
balance += amount;
}
public void debit(double fare) {
if (fare < MINIMUM_FARE) {
throw new IllegalArgumentException("fare cannot be below the minimum fare of " + MINIMUM_FARE);
}
if (fare > balance) {
throw new InsufficientBalanceException(
"cannot debit " + fare + ", balance is only " + balance);
}
balance -= fare;
}
public double getBalance() {
return balance;
}
}
solutions/MetroCardBoundaryTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MetroCardBoundaryTest {
private MetroCard card;
@BeforeEach
void createFreshCard() {
card = new MetroCard(100.0);
}
@Test
void debit_exactlyMinimumFare_succeeds() {
card.debit(MetroCard.MINIMUM_FARE);
assertEquals(90.0, card.getBalance());
}
@Test
void debit_exactlyFullBalance_leavesZeroBalance() {
card.debit(100.0);
assertEquals(0.0, card.getBalance());
}
}
solutions/MetroCardTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MetroCardTest {
private MetroCard card;
@BeforeEach
void createFreshCard() {
card = new MetroCard(100.0);
}
@Test
@DisplayName("recharge adds to the balance")
void recharge_positiveAmount_increasesBalance() {
card.recharge(50.0);
assertEquals(150.0, card.getBalance());
}
@Test
void recharge_zeroOrNegative_throwsIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> card.recharge(0.0));
assertThrows(IllegalArgumentException.class, () -> card.recharge(-5.0));
}
@Test
void debit_validFare_decreasesBalance() {
card.debit(30.0);
assertEquals(70.0, card.getBalance());
}
@Test
void debit_belowMinimumFare_throwsIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> card.debit(5.0));
}
@Test
void debit_moreThanBalance_throwsInsufficientBalanceExceptionWithClearMessage() {
InsufficientBalanceException error = assertThrows(
InsufficientBalanceException.class,
() -> card.debit(500.0));
assertEquals("cannot debit 500.0, balance is only 100.0", error.getMessage());
}
}
solutions/MetroCardWithSms.java
public class MetroCardWithSms {
public static final double MINIMUM_FARE = 10.0;
private final String phoneNumber;
private double balance;
private final SmsGateway smsGateway;
public MetroCardWithSms(String phoneNumber, double openingBalance, SmsGateway smsGateway) {
if (openingBalance < 0) {
throw new IllegalArgumentException("opening balance cannot be negative: " + openingBalance);
}
this.phoneNumber = phoneNumber;
this.balance = openingBalance;
this.smsGateway = smsGateway;
}
public void recharge(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("recharge amount must be positive: " + amount);
}
balance += amount;
smsGateway.send(phoneNumber, "Recharge of Rs " + amount + " successful. New balance: Rs " + balance);
}
public double getBalance() {
return balance;
}
}
solutions/MetroCardWithSmsTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MetroCardWithSmsTest {
private FakeSmsGateway smsGateway;
private MetroCardWithSms card;
@BeforeEach
void createFreshCard() {
smsGateway = new FakeSmsGateway();
card = new MetroCardWithSms("9800000001", 100.0, smsGateway);
}
@Test
void recharge_success_sendsExactlyOneConfirmationSms() {
card.recharge(50.0);
assertEquals(1, smsGateway.messagesSent().size());
assertTrue(smsGateway.messagesSent().get(0).contains("New balance: Rs 150.0"));
}
@Test
void recharge_success_sendsSmsToTheCardsOwnPhoneNumber() {
card.recharge(50.0);
assertTrue(smsGateway.messagesSent().get(0).startsWith("9800000001:"));
}
}
solutions/PostageCalculator.java
public class PostageCalculator {
public static double costFor(double weightInKg) {
if (weightInKg <= 0) {
throw new IllegalArgumentException("weight must be positive: " + weightInKg);
}
if (weightInKg <= 1) {
return 40.0;
}
if (weightInKg <= 5) {
return 80.0;
}
return 150.0;
}
}
solutions/PostageCalculatorTest.java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PostageCalculatorTest {
@ParameterizedTest(name = "{0} kg costs {1}")
@CsvSource({
"0.5, 40.0",
"1.0, 40.0",
"1.5, 80.0",
"5.0, 80.0",
"5.5, 150.0"
})
void costFor_variousWeights_matchExpected(double weightInKg, double expected) {
assertEquals(expected, PostageCalculator.costFor(weightInKg), 0.001);
}
@ParameterizedTest(name = "weight {0} is invalid")
@ValueSource(doubles = {0.0, -1.0, -10.5})
void costFor_nonPositiveWeight_throwsForEveryValue(double weightInKg) {
assertThrows(IllegalArgumentException.class, () -> PostageCalculator.costFor(weightInKg));
}
}
solutions/RechargeMathTest.java
// Exercise 7: Reproduce and fix a real test failure
//
// Real transcript, with the bug still in place (expected 135.0 instead of 125.0):
//
// $ javac -cp .:lib/junit-platform-console-standalone-1.14.5.jar RechargeMathTest.java
// $ java -jar lib/junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class RechargeMathTest --details=tree --disable-ansi-colors
// ...
// │ └─ recharge_twentyFive_balanceUpdatesCorrectly() ✘ expected: <135.0> but was: <125.0>
// ...
// [ 1 tests failed ]
// $ echo "EXIT:$?"
// EXIT:1
//
// Fix: 100.0 + 25.0 is really 125.0, not 135.0 -- the expected value was wrong, not the code.
//
// $ java -jar lib/junit-platform-console-standalone-1.14.5.jar execute -cp . --select-class RechargeMathTest --details=tree --disable-ansi-colors
// ...
// │ └─ recharge_twentyFive_balanceUpdatesCorrectly() ✔
// ...
// [ 1 tests successful ]
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RechargeMathTest {
private MetroCard card;
@BeforeEach
void createFreshCard() {
card = new MetroCard(100.0);
}
@Test
void recharge_twentyFive_balanceUpdatesCorrectly() {
card.recharge(25.0);
assertEquals(125.0, card.getBalance());
}
}
solutions/SmsGateway.java
public interface SmsGateway {
void send(String phoneNumber, String message);
}
solutions/Temperature.java
public class Temperature {
public static double celsiusToFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32;
}
}
solutions/TemperatureTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TemperatureTest {
@Test
void celsiusToFahrenheit_freezingPoint_returns32() {
double result = Temperature.celsiusToFahrenheit(0);
assertEquals(32.0, result, 0.01);
}
@Test
void celsiusToFahrenheit_bodyTemperature_returns98Point6() {
double result = Temperature.celsiusToFahrenheit(37);
assertEquals(98.6, result, 0.01);
}
}
solutions/WeatherConversionTest.java
// Exercise 2: Fix the broken test (the fixed version)
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class WeatherConversionTest {
@Test
void celsiusToFahrenheit_freezingPoint_returns32() {
double result = Temperature.celsiusToFahrenheit(0);
assertEquals(32.0, result, 0.01);
}
@Test
void celsiusToFahrenheit_bodyTemperature_returns98Point6() {
double result = Temperature.celsiusToFahrenheit(37);
assertEquals(98.6, result, 0.01);
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
java -cp . MyTest to run a test |
A test class has no main method — java fails with Error: Main method not found in class MyTest, please define the main method as: public static void main(String[] args) |
Run through the launcher: java -jar junit-platform-console-standalone-1.14.5.jar execute -cp . --scan-class-path |
javac MyTest.java with no -cp |
import org.junit.jupiter.api.Test; does not exist without the jar on the classpath |
javac -cp junit-platform-console-standalone-1.14.5.jar MyTest.java |
private void myTest() with @Test |
Compiles fine, but JUnit prints a discovery warning ("must not be private. It will not be executed.") and runs 0 tests from that method | Make the method package-private (no modifier) or public |
assertEquals(1180.0, result) on a double |
Exact floating-point equality is unreliable (IEEE 754) | assertEquals(1180.0, result, 0.001) — always pass a delta for double/float |
Swapping expected and actual |
The failure message reads backwards: "expected 944.0 but was 940.0" becomes confusing when the literal in your test is actually the wrong one | assertEquals(expected, actual) — the known-correct value always comes first |
One assertEquals per method, with 10 methods that only change one number |
Hard to scan, and adding a new case means copy-pasting a whole method | @ParameterizedTest + @CsvSource/@ValueSource — one body, many rows |
A test that creates a real ConsoleAlertService and checks System.out |
Slow, fragile, and tests the console instead of your logic | A hand-written fake (Section 9) that records what it was asked to do |
Running javadoc in a folder with test files, no -classpath |
javadoc still parses every .java file in the (default) package to build its picture, including ones needing JUnit to resolve |
Pass -classpath pointing at the same jar used to compile, even when not documenting the test files |
| Treating a red test as "the test must be wrong" | Half the time the test caught a real bug in the code | Read the stack trace's first line inside your own code, then decide which side is actually wrong |
Quick recap
- An automated test writes down "what should this be?" once, so it can be checked again in milliseconds, forever — a manual look-and-decide check does not scale past a few methods.
- Without Maven (until Part 15), JUnit 5 runs via one jar:
junit-platform-console-standalone-1.14.5.jar, named on both thejavac -cpand thejava -jar ... execute -cpcommand. @Testmarks a test method;assertEquals/assertTrue/assertThrows/assertAllcheck the result; adeltaargument is required for comparingdoubles; a message argument makes a failure legible at a glance.@BeforeEachgives every test a clean, independent starting point;@BeforeAll/@AfterAllrun once per class and must bestatic.@ParameterizedTestwith@CsvSource/@ValueSourcereplaces many near-identical test methods with one body and a table of inputs.- A hand-written test double (a small class implementing the same interface, recording what happened) tests code with real dependencies, with no mocking library needed yet.
- Test behaviour and edges and promised errors; skip trivial getters, the JDK itself, and private implementation details.
javadocturns/** ... */comments into real HTML and warns about undocumented public methods;java.util.logginggives levelled, filterable output the JDK ships for free.- A breakpoint plus step over/into/out replaces a
println-and-delete debugging cycle;git add/commit/pushsave and back up the work itself.
Checklist
- I downloaded and SHA-1-verified
junit-platform-console-standalone-1.14.5.jarintoexamples/lib/, and ran--versionon it. - I compiled and ran
DiscountCalculatorTestand saw a green tree, with real counts matching what I wrote. - I broke a test on purpose (
BrokenTest.java), read the real failure output end to end, and understood every line of it. - I wrote a test class with
@BeforeEachcreating fresh state, and explained out loud why that matters. - I wrote at least one
@ParameterizedTestwith@CsvSourceor@ValueSource. - I wrote a hand-rolled fake for an interface and used it to assert on behaviour a real implementation could not safely prove in a test.
- I ran
javadocon a class of mine, read awarning: no comment, and fixed it. - I set a breakpoint in an IDE, ran a test in debug mode, and stepped over/into/out at least once.
- I ran the full 18-test suite in
examples/bank-and-discount/and got a 100% green tree myself. - I committed this part's code with Git and pushed it to a GitHub repository.