0
0
JUnittesting~5 mins

Unit testing concept in JUnit

Choose your learning style9 modes available
Introduction

Unit testing helps check small parts of your code to make sure they work right. It finds mistakes early so fixing is easier.

When you write a new function and want to check it works as expected.
Before adding big changes to your code to avoid breaking things.
When fixing bugs to confirm the fix works and nothing else breaks.
To make sure each part of your program does its job correctly.
When you want to automate checks so you don't test manually every time.
Syntax
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class MyClassTest {
    @Test
    void testMethod() {
        // Arrange
        MyClass obj = new MyClass();
        
        // Act
        int result = obj.methodToTest();
        
        // Assert
        int expectedValue = 0; // define expectedValue appropriately
        assertEquals(expectedValue, result);
    }
}

Use @Test annotation to mark a method as a test.

Assertions like assertEquals check if the result matches what you expect.

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

class CalculatorTest {
    @Test
    void testAdd() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }
}
This test checks if the isEmpty method correctly identifies empty and non-empty strings.
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class StringUtilsTest {
    @Test
    void testIsEmpty() {
        assertTrue(StringUtils.isEmpty(""));
        assertFalse(StringUtils.isEmpty("abc"));
    }
}
Sample Program

This test checks if multiplying 4 by 5 returns 20 using the multiply method.

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

class MathUtils {
    int multiply(int a, int b) {
        return a * b;
    }
}

class MathUtilsTest {
    @Test
    void testMultiply() {
        MathUtils math = new MathUtils();
        int result = math.multiply(4, 5);
        assertEquals(20, result);
    }
}
OutputSuccess
Important Notes

Write one test for each small piece of code (method or function).

Keep tests simple and clear to understand.

Run tests often to catch problems early.

Summary

Unit tests check small parts of code to find errors early.

Use @Test and assertions like assertEquals in JUnit.

Good unit tests make your code more reliable and easier to fix.