Module 5 · A real program, end to end Lesson 14 of 15
Unit tests with JUnit
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.
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.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
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.
