0
0
JUnittesting~3 mins

Why @Test annotation in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could catch bugs instantly without running your program by hand every time?

The Scenario

Imagine you have a big Java program and you want to check if each part works correctly. You try running the program and checking results by hand every time you make a change.

The Problem

Manually running the program and checking results is slow and tiring. You might miss errors or forget to test some parts. It's easy to make mistakes and hard to keep track of what you tested.

The Solution

The @Test annotation lets you mark methods as tests. The testing tool runs these tests automatically and tells you if they pass or fail. This saves time and avoids human errors.

Before vs After
Before
public void checkAddition() {
  int result = add(2, 3);
  if (result != 5) {
    System.out.println("Test failed");
  }
}
After
@Test
public void checkAddition() {
  assertEquals(5, add(2, 3));
}
What It Enables

With @Test, you can run many tests quickly and get clear results, making your code more reliable and easier to improve.

Real Life Example

A developer changes a feature and runs all @Test methods to instantly see if anything broke, avoiding bugs before users find them.

Key Takeaways

Manual testing is slow and error-prone.

@Test marks methods to run automatically as tests.

This makes testing faster, safer, and more organized.