0
0
JUnittesting~5 mins

First JUnit test

Choose your learning style9 modes available
Introduction

JUnit tests help check if your code works correctly. They catch mistakes early so you can fix them fast.

You want to check if a simple method returns the right result.
You want to make sure a bug you fixed does not come back.
You want to test small parts of your program before combining them.
You want to run tests automatically every time you change code.
Syntax
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class MyTest {
    @Test
    void testMethod() {
        // test code here
        int expected = 0; // example expected value
        int actual = 0;   // example actual value
        assertEquals(expected, actual);
    }
}

The @Test annotation marks a method as a test.

Use assertions like assertEquals to check results.

Examples
This test checks if 2 + 3 equals 5.
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {
    @Test
    void additionTest() {
        int sum = 2 + 3;
        assertEquals(5, sum);
    }
}
This test checks if the length of "hello" is 5.
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class StringTest {
    @Test
    void lengthTest() {
        String text = "hello";
        assertEquals(5, text.length());
    }
}
Sample Program

This test checks if 4 times 5 equals 20. If yes, the test passes.

JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class SimpleTest {
    @Test
    void multiplyTest() {
        int result = 4 * 5;
        assertEquals(20, result);
    }
}
OutputSuccess
Important Notes

Each test method should be independent and test one thing.

Use clear names for test methods to know what they check.

Run tests often to catch problems early.

Summary

JUnit tests check if code works as expected.

Use @Test to mark test methods.

Assertions compare expected and actual results.