Part 10 / Topic 4 of 12
Naming a test, and @DisplayName
A test's name is read far more often than its body — in a failure report, in a teammate's terminal, in a CI log. This course's convention, used from here on:
methodUnderTest_condition_expectedResult
void finalPrice_negativePrice_throwsIllegalArgumentException() { ... }
void withdraw_moreThanBalance_throwsInsufficientFundsExceptionWithClearMessage() { ... }
Read one of these without opening the file: you already know what is being tested, under what condition, and what should happen. @DisplayName adds a human sentence on top, shown instead of the method name in reports — useful for names too long to read comfortably, or ones a non-Java reader (a PM, a tester) might see:
@Test
@DisplayName("no discount still adds 18% GST")
void finalPrice_noDiscount_addsGst() {
assertEquals(1180.0, DiscountCalculator.finalPrice(1000.0), 0.001);
}
The tree output from Section 3 showed exactly this: finalPrice_noDiscount_addsGst() versus no discount still adds 18% GST for the one test carrying @DisplayName — compare the full suite's tree in Section 12 to see both styles side by side. Pick one habit for a whole project; mixing "sometimes @DisplayName, sometimes not, with no rule" is worse than either rule alone.
Arrange-Act-Assert
Inside a test body, the same three-part shape repeats:
@Test
void finalPrice_withPercentOff_discountsThenAddsGst() {
// Arrange
double price = 1000.0;
double percentOff = 20.0;
// Act
double result = DiscountCalculator.finalPrice(price, percentOff);
// Assert: 1000 - 20% = 800, then +18% GST = 944
assertEquals(944.0, result, 0.001, "800 after discount, then 18% GST should be 944");
}
Arrange the inputs, Act by calling the one thing under test, Assert on the result. The comments are optional once the habit is automatic; the shape is not. A test that arranges, acts and asserts three different things in one method is a sign it should be three tests.
Done here? The practice set for Part 10 — including the solutions — is on the part page.