Practice: testing basics
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
ShopLite has tests now, but are they good ones? A test can be slow, flaky, unreadable, or never run at all. This optional checkpoint trains you to spot each problem and apply the standard fix.
Classifying a test: look at what it touches
Each test below is classified by what it touches, not by its name. Read the output, then try the rounds.
Example 1 · Classify by what the test touches
import java.util.List;
record TestInfo(String name, boolean realDatabaseOrFiles, boolean realJson, boolean runningAppOverHttp) { String kind() { if (runningAppOverHttp) return "end-to-end"; if (realDatabaseOrFiles || realJson) return "integration"; return "unit"; }}
public class ClassifyTestsDemo { public static void main(String[] args) { List<TestInfo> tests = List.of( new TestInfo("OrderItemTest.lineTotalIsPriceTimesQuantity", false, false, false), new TestInfo("OrderServiceIT.outOfStockSavesNothing", true, false, false), new TestInfo("ProductControllerTest.invalidBodyGives400", false, true, false), new TestInfo("ShopliteApiSmokeIT.healthIsUp", true, true, true), new TestInfo("JwtPropertiesTest.rejectsAShortKey", false, false, false));
for (TestInfo t : tests) { System.out.printf("%-48s %s%n", t.name(), t.kind()); } }}OrderItemTest.lineTotalIsPriceTimesQuantity unit OrderServiceIT.outOfStockSavesNothing integration ProductControllerTest.invalidBodyGives400 integration ShopliteApiSmokeIT.healthIsUp end-to-end JwtPropertiesTest.rejectsAShortKey unit
What this code does
- The decision uses only what each test touches, checked from the widest to the narrowest: the running app over HTTP, then real infrastructure such as MySQL or JSON conversion, then nothing but plain objects.
ProductControllerTestends inTest, but it runs the controller with real JSON conversion (a Spring web slice), so it is a small integration test even though Surefire runs it with the unit tests.
To classify a test, ignore its name and annotations and ask what it touches. Only plain objects: unit. A real database, file or JSON mapper together with your code: integration. The whole running app through HTTP: end-to-end.
A name can mislead: OrderServiceTest with @SpringBootTest and MySQL is an integration test, whatever it is called. In ShopLite such classes end in IT, so the name and the kind agree and Failsafe runs them.
Predict the output
What kind of test is it?
Look at what the test touches, not at its name.
Round 1 of 4
What kind of test is this?
Slow, flaky or unreadable: the warning signs
This test is flaky: it reads today's date and uses a shared counter. The fixed version passes in a Clock and keeps its counter in the object.
Example 2 · Fixing a flaky test: order numbers built from the date and a static counter
import java.time.Clock;import java.time.Instant;import java.time.LocalDate;import java.time.ZoneId;import java.time.format.DateTimeFormatter;
class OrderNumbersFlaky { static int counter = 0; // shared by every test
static String next() { counter++; return "ORD-" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + counter; }}
class OrderNumbers { private final Clock clock; private int counter = 0;
OrderNumbers(Clock clock) { this.clock = clock; }
String next() { counter++; return "ORD-" + LocalDate.now(clock).format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + counter; }}
public class FlakyOrderNumberDemo { public static void main(String[] args) { OrderNumbersFlaky.next(); // another test ran first System.out.println("flaky test sees: " + OrderNumbersFlaky.next().replaceAll("\\d{8}", "<today>"));
Clock oct16 = Clock.fixed(Instant.parse("2026-10-16T06:00:00Z"), ZoneId.of("Asia/Kolkata")); OrderNumbers numbers = new OrderNumbers(oct16); String first = numbers.next(); System.out.println("fixed test sees: " + first + " -> " + (first.equals("ORD-20261016-1") ? "PASS" : "FAIL")); }}flaky test sees: ORD-<today>-2 fixed test sees: ORD-20261016-1 -> PASS
What this code does
- The first version has two hidden inputs: today's date and a
staticcounter that other tests also move. A test expectingORD-20261016-1passes on one day, in one test order, and fails otherwise. (The date is hidden as<today>in the printout so this demo prints the same on any day.) - The fixed version takes a
Clockand keeps its counter in the object, so each test createsnew OrderNumbers(fixedClock)and always sees the same first number.
A slow test sleeps, starts Spring or a database when it only checks a rule, or loops over far more data than needed. A flaky test reads the real clock, uses unseeded random values, shares static state or calls the network. An unreadable test has a name like test1, unexplained numbers and many checks for different rules.
The fixes are always the same: move the rule into a plain class and unit test it, pass a Clock and a seeded Random, create fresh objects in every test, and split a big test into small named ones.
Find the bug
Spot the warning sign
Tap the line that makes the test slow or flaky, then read the fix.
This passes only on 16 October 2026.
Round 1 of 3Unreadable tests: magic numbers and vague names
Both tests below check the same fee and both pass. Only the second one tells a reader why the number is right.
Example 3 · Unreadable versus readable: the same fee test
import java.math.BigDecimal;import java.math.RoundingMode;
public class ReadableTestDemo { static BigDecimal hostelFeeWithGst(BigDecimal fee) { return fee.multiply(new BigDecimal("1.18")).setScale(2, RoundingMode.HALF_UP); }
static void assertEquals(Object expected, Object actual) { if (!expected.equals(actual)) throw new AssertionError("expected " + expected + " but was " + actual); }
// Unreadable: what is 1416.00? Is it right? static void test1() { assertEquals(new BigDecimal("1416.00"), hostelFeeWithGst(new BigDecimal("1200.00"))); }
// Readable: named values and a sentence for a name static final BigDecimal MONTHLY_FEE = new BigDecimal("1200.00"); static final BigDecimal GST_ON_FEE = new BigDecimal("216.00"); // 18% of 1200.00
static void feeIncludes18PercentGst() { BigDecimal expected = MONTHLY_FEE.add(GST_ON_FEE); assertEquals(expected, hostelFeeWithGst(MONTHLY_FEE)); }
public static void main(String[] args) { test1(); System.out.println("PASS test1"); feeIncludes18PercentGst(); System.out.println("PASS feeIncludes18PercentGst (1200.00 + 216.00 GST)"); }}PASS test1 PASS feeIncludes18PercentGst (1200.00 + 216.00 GST)
What this code does
- Both tests check the same thing and both pass. Only the second one tells a reader why 1416.00 is correct: the fee plus 18% GST of 216.00.
- If the GST rate ever changes to 12%, the readable test fails with a name and values that explain the rule at once;
test1just says a number is wrong.
A magic number is a value in code whose meaning is not written down, such as assertEquals(1416, fee(1200)). The reader cannot tell whether 1416 is right without redoing the maths.
A readable test names its values (TUITION, GST_18_PERCENT), shows how the expected value is built, or at least explains it in a short comment, and its method name says the rule in words.
Tests that Maven never runs
A green build can hide a test that never ran. Compare the two builds below, and look for your class name in the output.
Example 4 · A green build that runs nothing, and the fix
Runs in: a terminal in a plain Maven project with JUnit 5
# Before: src/test/java/com/shoplite/pricing/GstCheck.java, with import org.junit.Testmvn test# After: renamed to GstTest.java, import org.junit.jupiter.api.Testmvn test$ mvn test ... [INFO] --- surefire:3.5.6:test (default-test) @ shop-pricing --- [INFO] No tests to run. [INFO] BUILD SUCCESS $ mvn test ... [INFO] --- surefire:3.5.6:test (default-test) @ shop-pricing --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [INFO] Running com.shoplite.pricing.GstTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 s -- in com.shoplite.pricing.GstTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
What this code does
- The first build is green, but "No tests to run" gives it away:
GstCheckdoes not match Surefire's name patterns, so the class was never looked at. - After renaming the class and using the Jupiter
@Testimport, the class is listed with its three tests. Always look for your test class in the output, not just for BUILD SUCCESS.
Look at the Surefire output: if your class is not listed or the summary says Tests run: 0, the tests were not found.
The four usual causes are a test under src/main/java, a class name that does not end in Test, the JUnit 4 import org.junit.Test, and a private test method. For *IT classes, check that Failsafe is configured and that you ran mvn verify.
Order of execution
Check that your tests ran
Put the steps in order for finding out whether a green build ran your tests.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Classify each test and print one line per test.
GradeTest.ninetyIsA: callsGrade.of(90).StudentRepositoryIT.savesStudent: saves to the test MySQL database.ResultApiE2E.publishedResultIsVisible: starts the app, callsGET /results/21over HTTP.FeeCsvIT.readsFeeFile: reads a real CSV file from a temp folder.AttendanceTest.belowSeventyFivePercentIsShort: plain object.
GradeTest: unit StudentRepositoryIT: integration ResultApiE2E: end-to-end FeeCsvIT: integration AttendanceTest: unit
Exercise 2· Easy
Write a self-checking unit test for static int sleeperFare(int km): Rs 1 per km, with a minimum fare of Rs 150. Check 100 km (150), 150 km (150) and 600 km (600), printing PASS lines with sentence names.
PASS shortTripsPayTheMinimumFare PASS exactly150KmPays150 PASS longTripsPayPerKm
Exercise 3· Medium
Exam results go live at 10:00 on 1 June 2026 (India time). This class is flaky to test. Give it a Clock, then check that at 09:59 the results are hidden and at 10:00 they are visible (04:29 and 04:30 UTC).
class ResultPortal { static final LocalDateTime GO_LIVE = LocalDateTime.of(2026, 6, 1, 10, 0);
boolean resultsVisible() { return !LocalDateTime.now().isBefore(GO_LIVE); }}09:59 visible: false 10:00 visible: true
Exercise 4· Medium
These two tests share a static waiting list for a college fest and pass only in one order. Rewrite them so each test builds its own WaitingList, then run them in both orders.
static List<String> waiting = new ArrayList<>();
static void joiningAddsToTheEnd() { waiting.add("Asha"); waiting.add("Ravi"); check("Ravi", waiting.get(1)); }static void firstInLineIsServedFirst() { waiting.add("Kiran"); check("Kiran", waiting.remove(0)); }order 1: PASS PASS order 2: PASS PASS
Exercise 5· Medium
Split this unreadable test into three named tests with a tiny runner, so all failures are reported. The scholarship rule: 90+ marks get 50% off a fee of Rs 80000, 75 to 89 get 25%, below 75 nothing. The code has a bug at exactly 75. Print one line per test.
static int fee(int marks) { if (marks >= 90) return 40000; if (marks > 75) return 60000; // bug return 80000;}
static void test() { check(40000, fee(95)); check(60000, fee(75)); check(80000, fee(60));}PASS ninetyPlusGetsHalfOff FAIL exactlySeventyFiveGetsAQuarterOff: expected 60000 but was 80000 PASS belowSeventyFivePaysFullFee
Exercise 6· Medium
mvn verify in a plain Maven project prints Tests run: 12 for Surefire but never runs PaymentGatewayIT, and ReportsTest in src/main/java causes a compile error about org.junit not existing. Write the two fixes, one per line.
Add maven-failsafe-plugin with the integration-test and verify goals so *IT classes run in mvn verify Move ReportsTest from src/main/java to src/test/java (JUnit has test scope, so main code cannot see it)
Exercise 7· Hard
A college fest picks a lucky-draw winner from registrations, but only on the fest day (20 Dec 2026). The code uses new Random() and LocalDate.now(). Refactor it to take a Random and a Clock, then write tests: before the fest day the result is not yet; on the fest day with new Random(5) the same winner is picked twice in a row (two separate draws with two Random(5) objects), and the winner is one of the registered names.
class LuckyDraw { String winner(List<String> names) { if (LocalDate.now().isBefore(LocalDate.of(2026, 12, 20))) return "not yet"; return names.get(new Random().nextInt(names.size())); }}PASS beforeFestDayThereIsNoWinner PASS sameSeedGivesSameWinner PASS winnerIsARegisteredStudent
Exercise 8· Hard
Expose hidden order dependence: three tests share a static list. Run them once in written order and once in an order shuffled with Collections.shuffle(order, new Random(2)), and print the results of both runs. The same tests fail in one order and pass in the other, which proves they depend on each other. Use test names as given and clear the list before each run (not before each test).
static List<String> bag = new ArrayList<>();// "addPen": bag.add("pen"); expect size 1// "addBook": bag.add("book"); expect size 2// "bagStartsEmpty": expect size 0written: addPen PASS, addBook PASS, bagStartsEmpty FAIL shuffled: bagStartsEmpty PASS, addPen PASS, addBook PASS
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: Mini project: a ShopLite test plan and first tests