📊 We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 5 · Lesson 14 of 15

0% Exit to course

Module 5 · A real program, end to end Lesson 14 of 15

Unit tests with JUnit

Learning objective

A unit test calls one method and checks the result. For a fresher it is proof the code works, and for a team it is the safety net that lets anyone change code without fear.

The concept

Test the edges, not the middle - an empty list, a single element, a value exactly on a threshold - because that is where bugs live.

A test that never fails is not a test; change the code on purpose, watch it go red, then put it back. That red proves the test does something.

Java
class StudentServiceTest {
    @Test
    void averageOfMarks() {
        var service = new StudentService(new FakeRepo(List.of(70, 80)));
        assertEquals(75.0, service.average(), 0.001);
    }

    @Test
    void averageOfNothingIsZero() {
        var service = new StudentService(new FakeRepo(List.of()));
        assertEquals(0.0, service.average(), 0.001);
    }
}

Worked example

assertEquals(75.0, service.average(List.of(70, 80)), 0.001) runs with one command and fails loudly the moment the rule breaks.

Your practice task

Write three JUnit tests for your service: a normal case, an empty input and a boundary value.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

Test the edges, not the middle - an empty list, a single element, a value exactly on a threshold - because that is where bugs live.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.

Next recommended course Python for Absolute Beginners