🧠 What is JUnit 5?

Think of JUnit 5 like a toolbox for testing Java programs. When you’re writing code, you want to make sure it works properly. JUnit helps you do that by letting you write small test programs that automatically check if your real code is doing what it should.


🏗️ What’s Inside JUnit 5?

JUnit 5 is made up of 3 main pieces (like building blocks):

1. JUnit Platform

  • It’s the engine room.
  • It runs your tests and connects with tools like IDEs (e.g., IntelliJ, Eclipse) or build systems (e.g., Maven, Gradle).

2. JUnit Jupiter

  • This is where you write your new tests using simple Java code.
  • It has the modern test-writing style like: javaCopyEdit@Test void myTest() { // check something here }

3. JUnit Vintage

  • This is for people who wrote tests the old way (using JUnit 3 or 4).
  • It helps you run old tests with the new JUnit 5 platform.

✍️ How Do You Write a Test?

Imagine you want to test if your calculator adds numbers correctly:

javaCopyEdit@Test
void testAddition() {
    int result = 2 + 2;
    assertEquals(4, result);  // Check if 2+2 really equals 4
}
  • @Test: Tells JUnit that this method is a test.
  • assertEquals: Makes sure the answer is correct.

📌 Other Useful Things in JUnit

What it doesKeywordMeaning in plain English
Run before all tests@BeforeAll“Do this once before starting the tests”
Run before each test@BeforeEach“Do this before every single test”
Run after each test@AfterEach“Clean up after every test”
Skip a test@Disabled“Ignore this test for now”
Make a nicer test name@DisplayName“Give the test a human-friendly name”

🤖 Why Use JUnit?

  • It saves time by automating test checks.
  • It helps you catch bugs early.
  • It’s easy to use with other tools and build systems.
  • It’s standard — used in almost every serious Java project.

Leave a Comment