How to Write Tests in JUnit: Simple Guide with Examples
To write a test in
JUnit, create a public method annotated with @Test inside a class. Use assertions like Assertions.assertEquals() to check expected results. Run the test with a JUnit runner to see if it passes or fails.Syntax
In JUnit, a test method must be annotated with @Test. The method should be public, return void, and contain assertions to verify behavior.
@Test: Marks the method as a test.- Method name: Describes what is tested.
- Assertions: Check if the actual result matches the expected.
java
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class ExampleTest { @Test public void testAddition() { int sum = 2 + 3; assertEquals(5, sum); } }
Example
This example shows a simple test that checks if adding two numbers returns the correct sum. It uses assertEquals to compare the expected value with the actual result.
java
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test public void testAdd() { Calculator calc = new Calculator(); int result = calc.add(10, 20); assertEquals(30, result, "10 + 20 should equal 30"); } } class Calculator { public int add(int a, int b) { return a + b; } }
Output
Test passed: testAdd()
Common Pitfalls
Common mistakes when writing JUnit tests include:
- Forgetting the
@Testannotation, so the method does not run as a test. - Using assertions incorrectly, such as reversing expected and actual values.
- Writing tests that depend on external state or order, causing flaky results.
- Not making test methods
public void.
java
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class WrongTest { // Missing @Test annotation - this test will not run public void testFail() { assertEquals(5, 2 + 2); // Wrong expected value } @Test public void testRight() { assertEquals(4, 2 + 2); // Correct assertion } }
Output
Test passed: testRight()
Test not run: testFail() (missing @Test annotation)
Quick Reference
Remember these tips when writing JUnit tests:
- Always annotate test methods with
@Test. - Use
assertEquals(expected, actual)for checking values. - Keep tests independent and repeatable.
- Name tests clearly to describe their purpose.
Key Takeaways
Annotate test methods with @Test to make JUnit recognize them as tests.
Use assertions like assertEquals to verify expected outcomes.
Test methods must be public and return void.
Avoid dependencies between tests to keep results reliable.
Name tests clearly to understand what they check at a glance.