Intermediate level · Module 5: Unit Testing with JUnit 5 · Lesson 1 of 3
Your First JUnit Tests
Write test methods with @Test and assertions, run them in IntelliJ and with Maven, and read the results.
In this lesson you will
- Write tests in the Arrange–Act–Assert pattern
- Run tests in the IDE and with mvn test
Key concepts
@TestassertEqualsArrange–Act–Asserttest runner
The lesson
A unit test checks one small piece of behaviour automatically. In JUnit 5 a test is a method annotated with @Test in a class under src/test/java. Assertions such as assertEquals(expected, actual) fail the test when the behaviour is wrong.
Structure each test in three parts: arrange the objects and data, act by calling the method under test, and assert the result. One test should check one behaviour, and its name should say what that behaviour is.
Tests run in the IDE with a click and from the terminal with mvn test. A green result means every assertion passed; a red one shows the expected and actual values, which usually points straight at the bug.
Step by step
- Create a test class WalletTest in src/test/java.
- Write a test that a deposit increases the balance.
- Run it in IntelliJ, then with mvn test.
- Break the deposit method on purpose and watch the test fail.
Practice activity
Write five tests for a Wallet class covering deposits, withdrawals and the starting balance.
Expected result: All five tests pass on correct code and at least one fails when a bug is introduced.
Check your understanding
-
Where are JUnit test classes stored in a Maven project?
Show answer
Under src/test/java.
-
What are the three parts of a well-structured test?
Show answer
Arrange, act and assert.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.