Testing with JUnit
Turn small methods into automated checks with @Test, assertions and parameterised tests.
- Mark each check with @Test so JUnit discovers it.
- Use assertEquals to compare actual and expected values.
- Use a parameterised test instead of copying near-identical tests.
- Name tests as behaviour under a condition, not method names.
In plain English
JUnit is a testing framework for Java that turns small methods into automated checks for your code. The @Test annotation marks a method as a test, so JUnit runs it and reports whether it passed. An assertion is a statement that compares an actual value to an expected value, and it fails the test when the two do not match. A parameterised test runs the same test body several times with different inputs supplied by a source, so you do not copy one test per example. Test structure means arranging input, acting on the code and asserting the result, and test names should describe the behaviour under a condition, such as shouldFailForEmptyTitle.
Step by step
- 1Add the JUnit 5 dependency to your build file.
- 2Create a test class named after the class under test.
- 3Write an @Test method that arranges, acts and asserts.
- 4Use assertEquals with the expected value first.
- 5Convert repeated examples into a parameterised test.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LessonTest {
@Test
void returnsTitle() {
Lesson lesson = new Lesson("Java", 12);
String title = lesson.title();
assertEquals("Java", title);
}
@ParameterizedTest
@ValueSource(ints = {1, 5, 120})
void storesMinutes(int minutes) {
Lesson lesson = new Lesson("Java", minutes);
assertEquals(minutes, lesson.minutes());
}
}Common mistakes
- Naming a test after the method instead of the behaviour hides what the test promises, so a reader must open the body to learn it.
- Writing assertEquals(actual, expected) swaps the arguments and produces confusing failure messages that mislabel the values.
- A parameterised test that asserts the same thing for every input proves little, so make the expected value vary with the input.
- Forgetting to import JUnit annotations fails to compile, because the test runner cannot discover methods without them.
Write your first assertion
Write a JUnit 5 test method that creates a Lesson with the title "Java" and asserts its title method returns "Java".
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LessonTest {
@Test
void returnsTitle() {
}
}In JUnit 5, what does the @Test annotation do?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.