These are the notes for Java episode 44. Ravi's chai stall app charges Rs 15 a cup with 10% off for 10 cups or more, and we need to know the bill is right after every change. Reading printed numbers misses a bug, and a home-made check() method stops at the first crash. So we invent a test framework, and meet Java's most popular one: JUnit (JUnit 5, also called JUnit Jupiter). Every program and test here was really compiled and run (javac 21, the JUnit 5 console launcher); the shell outputs are copied from those runs, with colours removed and long stack traces shortened where you see ….
The problem: how do we know the bill is right?
Real-life example: Ravi's chai stall. One cup is Rs 15. New offer: 10 cups or more get 10% off. Office orders of 10, 12 and 20 cups come in every day. Every time someone changes the billing code, the old rules must still work.
Attempt 1: run it and look
public class Main {
// Rs 15 a cup. 10 cups or more: 10% off.
static int total(int cups, int price) {
int sum = cups * price;
if (cups > 10) sum = sum - sum / 10;
return sum;
}
public static void main(String[] args) {
System.out.println(total(1, 15));
System.out.println(total(3, 15));
System.out.println(total(5, 15));
System.out.println(total(10, 15));
System.out.println(total(12, 15));
System.out.println(total(20, 15));
}
}
Output:
15
45
75
150
162
270
Did you spot the bug? 10 cups should cost 135 (150 minus 10%), but the program printed 150, and it looked perfectly normal. The condition is cups > 10 instead of cups >= 10. Our eyes are not a test, and nobody re-reads every number after every change.
Attempt 2: a home-made check() method
public class Main {
static int total(int cups, int price) {
int sum = cups * price;
if (cups > 10) sum = sum - sum / 10;
return sum;
}
static int share(int total, int people) { return total / people; }
static void check(String name, int expected, int actual) {
if (expected == actual) System.out.println("PASS " + name);
else System.out.println("FAIL " + name + ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) {
check("one cup", 15, total(1, 15));
check("ten cups", 135, total(10, 15));
check("split 150 by 0 people", 0, share(150, 0));
check("twelve cups", 162, total(12, 15));
}
}
Output:
PASS one cup
FAIL ten cups: expected 135, got 150
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.share(Main.java:7)
at Main.main(Main.java:16)
The computer caught the bug, but:
| Problem | What happened |
|---|---|
Checks live inside main |
they would ship with the app |
| One exception stops everything | the "twelve cups" check never ran |
Every project writes its own check() |
no standard report, no tools |
What we want: checks in a separate class, each check in its own method that runs on its own, and a runner that finds and runs them all and prints a report. That is a test framework. In Java: JUnit.
JUnit: your first test class
Real-life example: the teacher's answer key. The answer key is kept separate from the question paper (test class), each question is marked on its own (test method), the answer is compared with the key (assertion), and the teacher marks everything and writes the total (test runner).
A unit test is a small, automatic check of one small unit of code, usually one method.
Bill.java (still with the bug):
public class Bill {
// Rs 15 a cup. 10 cups or more: 10% off.
public static int total(int cups, int price) {
int sum = cups * price;
if (cups > 10) sum = sum - sum / 10;
return sum;
}
public static int share(int total, int people) {
return total / people;
}
}
BillTest.java:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BillTest {
@Test
void oneCup() {
assertEquals(15, Bill.total(1, 15));
}
@Test
void tenCupsGetTenPercentOff() {
assertEquals(135, Bill.total(10, 15));
}
@Test
void twelveCups() {
assertEquals(162, Bill.total(12, 15));
}
}
@Testmarks a test method. The runner finds methods by this annotation.- Test methods return
void, take no arguments, and are notprivate. The name says what is checked. assertEquals(expected, actual): expected first, actual second. Equal: the test passes. Different: it fails with both values.import static ...Assertions.*lets you writeassertEqualsinstead ofAssertions.assertEquals.- No
mainmethod: the runner calls the test methods.
Compile: JUnit is a library
JUnit isn't part of the JDK. It's a library: a .jar file of ready-made classes. Here we use the JUnit console launcher (junit-platform-console-standalone-<version>.jar, saved as junit.jar), which contains JUnit and a runner you can start from the terminal.
$ javac -d out Bill.java BillTest.java
BillTest.java:1: error: package org.junit.jupiter.api does not exist
import org.junit.jupiter.api.Test;
^
BillTest.java:2: error: package org.junit.jupiter.api does not exist
import static org.junit.jupiter.api.Assertions.*;
^
…
8 errors
javac doesn't know where JUnit is. Put it on the classpath (the list of places where Java looks for classes) with -cp:
$ javac -cp junit.jar -d out Bill.java BillTest.java && ls out
Bill.class
BillTest.class
-d out puts the compiled .class files in a folder called out.
Run the tests and read a failure
$ java -jar junit.jar execute -cp out --disable-banner -c BillTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BillTest ✔
│ ├─ twelveCups() ✔
│ ├─ oneCup() ✔
│ └─ tenCupsGetTenPercentOff() ✘ expected: <135> but was: <150>
└─ JUnit Vintage ✔
Failures (1):
JUnit Jupiter:BillTest:tenCupsGetTenPercentOff()
=> org.opentest4j.AssertionFailedError: expected: <135> but was: <150>
BillTest.tenCupsGetTenPercentOff(BillTest.java:12)
…
[ 2 tests successful ]
[ 1 tests failed ]
executeruns tests;-cp outis where our compiled classes are;-c BillTestselects the class;--disable-bannerhides a thank-you message.- Ignore the
JUnit Platform SuiteandJUnit Vintagelines: those are other test engines inside the launcher, with nothing to run. - The failure gives the test name, expected vs actual, and the file and line of the failing assertion.
- The other two tests still ran and passed.
- The order (
twelveCupsfirst) is JUnit's, not the order in the file. Tests must never depend on order.
Fix cups > 10 to cups >= 10, recompile, and run again:
$ java -jar junit.jar execute -cp out --disable-banner -c BillTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BillTest ✔
│ ├─ twelveCups() ✔
│ ├─ oneCup() ✔
│ └─ tenCupsGetTenPercentOff() ✔
└─ JUnit Vintage ✔
[ 3 tests successful ]
[ 0 tests failed ]
Running all the old tests after every change is regression testing. A regression is a bug that comes back, or a feature that used to work and broke.
How to write a good test
| Rule | Why |
|---|---|
| Arrange, Act, Assert | set up the data, call the method, check the result |
| One behaviour per test, named like a sentence | a failure tells you what broke |
| Test the edges: 0, 9, 10, 11 | our bug sat exactly at the boundary 10; 3 cups would never find it |
| Fast, automatic, independent, repeatable | you'll run them hundreds of times |
| Watch every new test fail once | a test that can never fail checks nothing |
assertThrows and test-driven development
Splitting a bill between zero people should not crash with / by zero deep inside. Ravi wants a clear message: people must be at least 1, as an IllegalArgumentException. We write the test first:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BillTest {
@Test
void oneCup() {
assertEquals(15, Bill.total(1, 15));
}
@Test
void tenCupsGetTenPercentOff() {
assertEquals(135, Bill.total(10, 15));
}
@Test
void twelveCups() {
assertEquals(162, Bill.total(12, 15));
}
@Test
void shareWithZeroPeopleIsRejected() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> Bill.share(150, 0));
assertEquals("people must be at least 1", e.getMessage());
}
}
assertThrows(Type.class, () -> code) runs the lambda (episode 36) and passes only if it throws that exception type. It returns the exception, so we can check its message too.
Red: the test fails first.
$ java -jar junit.jar execute -cp out --disable-banner -c BillTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BillTest ✔
│ ├─ shareWithZeroPeopleIsRejected() ✘ Unexpected exception type thrown, expected: <java.lang.IllegalArgumentException> but was: <java.lang.ArithmeticException>
│ ├─ twelveCups() ✔
│ ├─ oneCup() ✔
│ └─ tenCupsGetTenPercentOff() ✔
└─ JUnit Vintage ✔
Failures (1):
JUnit Jupiter:BillTest:shareWithZeroPeopleIsRejected()
=> org.opentest4j.AssertionFailedError: Unexpected exception type thrown, expected: <java.lang.IllegalArgumentException> but was: <java.lang.ArithmeticException>
BillTest.shareWithZeroPeopleIsRejected(BillTest.java:22)
…
Caused by: java.lang.ArithmeticException: / by zero
Bill.share(Bill.java:10)
[ 3 tests successful ]
[ 1 tests failed ]
The crash stayed inside its own test: the other three still ran.
Green: now write just enough code.
public class Bill {
// Rs 15 a cup. 10 cups or more: 10% off.
public static int total(int cups, int price) {
int sum = cups * price;
if (cups >= 10) sum = sum - sum / 10;
return sum;
}
public static int share(int total, int people) {
if (people < 1)
throw new IllegalArgumentException("people must be at least 1");
return total / people;
}
}
$ java -jar junit.jar execute -cp out --disable-banner -c BillTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BillTest ✔
│ ├─ shareWithZeroPeopleIsRejected() ✔
│ ├─ twelveCups() ✔
│ ├─ oneCup() ✔
│ └─ tenCupsGetTenPercentOff() ✔
└─ JUnit Vintage ✔
[ 4 tests successful ]
[ 0 tests failed ]
Test-driven development (TDD) is this loop: red (write a failing test), green (write just enough code to pass), refactor (clean up, with the tests proving nothing broke).
@BeforeEach: a fresh start for every test
Real-life example: the waiter who never clears the bill. Table 1 orders two chai (Rs 30). Table 2 orders one samosa, but the waiter writes it on the same page: Rs 50 for one samosa.
Order.java:
import java.util.ArrayList;
import java.util.List;
public class Order {
private final List<Integer> prices = new ArrayList<>();
public void add(String item, int price) { prices.add(price); }
public int total() {
int sum = 0;
for (int p : prices) sum += p;
return sum;
}
}
Two tests that share one static order:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class OrderTest {
static Order order = new Order(); // one order shared by every test
@Test
void twoChai() {
order.add("chai", 15);
order.add("chai", 15);
assertEquals(30, order.total());
}
@Test
void oneSamosa() {
order.add("samosa", 20);
assertEquals(20, order.total());
}
}
$ javac -cp junit.jar -d out Order.java OrderTest.java && java -jar junit.jar execute -cp out --disable-banner -c OrderTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ OrderTest ✔
│ ├─ twoChai() ✔
│ └─ oneSamosa() ✘ expected: <20> but was: <50>
└─ JUnit Vintage ✔
Failures (1):
JUnit Jupiter:OrderTest:oneSamosa()
=> org.opentest4j.AssertionFailedError: expected: <20> but was: <50>
OrderTest.oneSamosa(OrderTest.java:17)
…
[ 1 tests successful ]
[ 1 tests failed ]
Each test is right on its own; together one fails, and which one fails depends on the order. Tests must never share changing state.
The fix: a normal field, and @BeforeEach:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class OrderTest {
Order order;
@BeforeEach
void freshOrder() {
order = new Order(); // a new, empty order before EACH test
}
@Test
void twoChai() {
order.add("chai", 15);
order.add("chai", 15);
assertEquals(30, order.total());
}
@Test
void oneSamosa() {
order.add("samosa", 20);
assertEquals(20, order.total());
}
}
$ java -jar junit.jar execute -cp out --disable-banner -c OrderTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ OrderTest ✔
│ ├─ twoChai() ✔
│ └─ oneSamosa() ✔
└─ JUnit Vintage ✔
[ 2 tests successful ]
[ 0 tests failed ]
| Annotation | Runs |
|---|---|
@BeforeEach |
before every test method (setup) |
@AfterEach |
after every test method (cleanup) |
@BeforeAll |
once, before all tests in the class (must be static) |
@AfterAll |
once, after all tests (must be static) |
JUnit also creates a new object of the test class for every test method, so normal (non-static) fields start fresh anyway.
Parameterized tests: one test, many inputs
Five copy-pasted tests for 0, 1, 9, 10 and 11 cups? Use @ParameterizedTest with @CsvSource (comma-separated values: each string is one run).
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class TotalTest {
@ParameterizedTest
@CsvSource({ "1, 15", "9, 135", "10, 135", "11, 149", "0, 0" })
void totalForCups(int cups, int expected) {
assertEquals(expected, Bill.total(cups, 15));
}
}
$ javac -cp junit.jar -d out Bill.java TotalTest.java && java -jar junit.jar execute -cp out --disable-banner -c TotalTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ TotalTest ✔
│ └─ totalForCups(int, int) ✔
│ ├─ [1] 1, 15 ✔
│ ├─ [2] 9, 135 ✔
│ ├─ [3] 10, 135 ✔
│ ├─ [4] 11, 149 ✔
│ └─ [5] 0, 0 ✔
└─ JUnit Vintage ✔
[ 5 tests successful ]
[ 0 tests failed ]
The tests show something worth asking Ravi about: 9 cups and 10 cups both cost Rs 135, and 11 cups cost Rs 149 because integer division drops the half rupee (165 / 10 = 16). Writing tests makes you ask these questions before customers do.
The whole suite
$ javac -cp junit.jar -d out *.java && java -jar junit.jar execute -cp out --disable-banner --scan-classpath out
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ ├─ BillTest ✔
│ │ ├─ shareWithZeroPeopleIsRejected() ✔
│ │ ├─ twelveCups() ✔
│ │ ├─ oneCup() ✔
│ │ └─ tenCupsGetTenPercentOff() ✔
│ ├─ OrderTest ✔
│ │ ├─ twoChai() ✔
│ │ └─ oneSamosa() ✔
│ └─ TotalTest ✔
│ └─ totalForCups(int, int) ✔
│ ├─ [1] 1, 15 ✔
│ ├─ [2] 9, 135 ✔
│ ├─ [3] 10, 135 ✔
│ ├─ [4] 11, 149 ✔
│ └─ [5] 0, 0 ✔
└─ JUnit Vintage ✔
[ 11 tests successful ]
[ 0 tests failed ]
--scan-classpath out finds every test class in out: 11 tests in well under a second.
Common mistakes (and what you see)
Forgetting @Test:
import static org.junit.jupiter.api.Assertions.*;
class ForgotTest {
void tenCups() { // no @Test
assertEquals(999, Bill.total(10, 15));
}
}
$ java -jar junit.jar execute -cp out --disable-banner -c ForgotTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
[ 0 tests found ]
[ 0 tests successful ]
[ 0 tests failed ]
Not a pass: zero tests found. Always check the count.
Swapping expected and actual (with the old cups > 10 bug back):
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SwapTest {
@Test
void tenCups() {
assertEquals(Bill.total(10, 15), 135); // actual first: wrong order
}
}
$ java -jar junit.jar execute -cp out --disable-banner -c SwapTest
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ SwapTest ✔
│ └─ tenCups() ✘ expected: <150> but was: <135>
└─ JUnit Vintage ✔
Failures (1):
JUnit Jupiter:SwapTest:tenCups()
=> org.opentest4j.AssertionFailedError: expected: <150> but was: <135>
SwapTest.tenCups(SwapTest.java:7)
…
[ 0 tests successful ]
[ 1 tests failed ]
The message says expected 150, but 135 is what we wanted: backwards, and it sends you looking in the wrong place.
| Mistake | What you see | Fix |
|---|---|---|
| Compiling tests without JUnit on the classpath | error: package org.junit.jupiter.api does not exist |
javac -cp junit.jar ... |
Test method without @Test |
0 tests found |
add @Test |
assertEquals(actual, expected) |
expected: <150> but was: <135> (backwards) |
expected first |
A shared static object changed by tests |
expected: <20> but was: <50>, depending on order |
@BeforeEach and a normal field |
assertThrows but the code throws something else |
Unexpected exception type thrown, expected: <java.lang.IllegalArgumentException> but was: <java.lang.ArithmeticException> |
throw the exception you promised |
A private test method |
0 tests found (silently skipped) |
package-private or public |
Mini project: test a shopping cart
Cart.java:
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart {
private final Map<String, Integer> qty = new LinkedHashMap<>();
private final Map<String, Integer> price = new LinkedHashMap<>();
public void add(String item, int unitPrice, int count) {
if (count <= 0) throw new IllegalArgumentException("count must be positive");
qty.merge(item, count, Integer::sum);
price.put(item, unitPrice);
}
public void remove(String item) { qty.remove(item); price.remove(item); }
public int items() { return qty.values().stream().mapToInt(Integer::intValue).sum(); }
public int total() {
int sum = 0;
for (String item : qty.keySet()) sum += qty.get(item) * price.get(item);
return sum;
}
}
CartTest.java uses @DisplayName (a readable name in the report) and assertAll (checks several things and reports all failures, not just the first):
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.*;
class CartTest {
Cart cart;
@BeforeEach
void newCart() { cart = new Cart(); }
@Test
@DisplayName("an empty cart costs nothing")
void empty() {
assertAll(() -> assertEquals(0, cart.items()),
() -> assertEquals(0, cart.total()));
}
@Test
@DisplayName("adding the same item twice adds up the count")
void sameItemTwice() {
cart.add("chai", 15, 2);
cart.add("chai", 15, 1);
assertEquals(3, cart.items());
assertEquals(45, cart.total());
}
@Test
@DisplayName("removing an item takes it off the bill")
void remove() {
cart.add("chai", 15, 2);
cart.add("samosa", 20, 1);
cart.remove("chai");
assertEquals(20, cart.total());
}
@Test
@DisplayName("zero or negative counts are rejected")
void badCount() {
assertThrows(IllegalArgumentException.class, () -> cart.add("chai", 15, 0));
}
}
Output (tree part):
│ └─ CartTest ✔
│ ├─ removing an item takes it off the bill ✔
│ ├─ adding the same item twice adds up the count ✔
│ ├─ an empty cart costs nothing ✔
│ └─ zero or negative counts are rejected ✔
[ 4 tests successful ]
[ 0 tests failed ]
Practice
1. Test a leap-year method for 2024, 2025, 1900 and 2000.
Solution
public class Year {
public static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class YearTest {
@ParameterizedTest
@CsvSource({ "2024, true", "2025, false", "1900, false", "2000, true" })
void leapYears(int year, boolean expected) {
assertEquals(expected, Year.isLeap(year));
}
}
Output: [1] 2024, true ✔, [2] 2025, false ✔, [3] 1900, false ✔, [4] 2000, true ✔, 4 tests successful. 1900 is the edge case: divisible by 4 and by 100 but not by 400, so not a leap year.
2. TDD: write the tests for tip(total, percent) first (10% of 150 is 15; 5% of 135 rounds to 7; a negative percent is rejected), then the code.
Solution
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TipTest {
@Test
void tenPercentOf150() { assertEquals(15, Tip.tip(150, 10)); }
@Test
void roundsToNearestRupee() { assertEquals(7, Tip.tip(135, 5)); } // 6.75 -> 7
@Test
void negativePercentIsRejected() {
assertThrows(IllegalArgumentException.class, () -> Tip.tip(100, -5));
}
}
public class Tip {
// tip in whole rupees, rounded to the nearest rupee
public static int tip(int total, int percent) {
if (percent < 0) throw new IllegalArgumentException("percent cannot be negative");
return Math.round(total * percent / 100.0f);
}
}
Output: 3 tests successful.
3. A parameterized test for share() with 5 rows.
Solution
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class ShareTest {
@ParameterizedTest
@CsvSource({ "150, 1, 150", "150, 2, 75", "150, 4, 37", "0, 3, 0", "10, 3, 3" })
void share(int total, int people, int expected) {
assertEquals(expected, Bill.share(total, people));
}
}
Output: 5 tests successful. Note 150 / 4 = 37 and 10 / 3 = 3: integer division.
4. Make a test fail on purpose (change 135 to 136) and read the message. What are the three things it tells you?
Answer
The test's name, the expected and actual values (expected: <136> but was: <135>), and the file and line of the failing assertion.
Quick quiz
class CartTest {
@BeforeEach void setUp() { ... }
@Test void a() { ... }
@Test void b() { ... }
void c() { ... }
@Test void d() { ... }
}
How many times does setUp() run? A) once B) 3 times C) 4 times D) never
Answer
B) 3 times. @BeforeEach runs before every test, and only a, b and d are tests (c has no @Test).
Interview questions
- What is a unit test? A small, automatic, fast check of one unit of code (usually one method), independent of other tests.
- Why is
assertEquals(expected, actual)order important? The failure message is built from it; swapping them gives a backwards, misleading message. @BeforeEachvs@BeforeAll?@BeforeEachruns before every test;@BeforeAllruns once before all tests and must bestatic(by default).- How do you test that a method throws?
assertThrows(ExpectedException.class, () -> call()), which also returns the exception to check its message. - What is TDD? Write a failing test first (red), make it pass with the simplest code (green), then refactor.
- Why must tests be independent? JUnit doesn't promise an order; shared state makes tests pass or fail depending on order.
- What is regression testing? Re-running existing tests after a change to make sure nothing that worked broke.
- What is a parameterized test? One test method run many times with different inputs, e.g. with
@CsvSource.
Glossary
| Term | Meaning |
|---|---|
| Unit test | a small automatic check of one unit of code, usually one method |
| Test class | a separate class (e.g. BillTest) holding tests for one class |
| Test framework | a library that finds, runs and reports tests (JUnit) |
| JUnit / JUnit Jupiter | Java's most popular test framework; Jupiter is JUnit 5's programming model |
@Test |
annotation that marks a test method |
| Assertion | a check inside a test, e.g. assertEquals, assertThrows, assertTrue |
assertEquals(expected, actual) |
passes if the two values are equal |
assertThrows |
passes if the code throws the given exception type |
assertAll |
runs several assertions and reports all failures |
| Test runner | the program that runs the tests and prints the report (here the console launcher) |
| Library | ready-made code shipped as a .jar file |
Classpath (-cp) |
the list of places where Java looks for classes |
| Regression | a bug that comes back, or a feature that worked and broke |
| Regression testing | re-running old tests after every change |
| Arrange, Act, Assert | the three parts of a test: set up, call, check |
| Edge case / boundary | an input at the limit of a rule (9, 10, 11 cups) |
| TDD | test-driven development: red, green, refactor |
@BeforeEach / @AfterEach |
run before / after every test |
@BeforeAll / @AfterAll |
run once before / after all tests |
@ParameterizedTest |
a test run once per set of inputs |
@CsvSource |
gives inputs as comma-separated values |
@DisplayName |
a readable name for a test in the report |
Summary
- Reading printed output is not testing; a home-made
check()stops at the first crash. - A unit test is a small automatic check in a separate test class, in a method marked
@Test. assertEquals(expected, actual): expected first. Read failures: name, expected vs actual, file and line.- JUnit is a library: compile with
-cp junit.jar, run the console launcher. assertThrowstests exceptions; TDD is red, green, refactor.@BeforeEachgives every test a fresh start; never share changing state between tests.@ParameterizedTest+@CsvSourcetests many edge cases with one method.- Next episode: Maven and Gradle, which download JUnit and run all the tests with one command.