Introduction
Unit testing helps check small parts of your code to make sure they work right. It finds mistakes early so fixing is easier.
Unit testing helps check small parts of your code to make sure they work right. It finds mistakes early so fixing is easier.
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.
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)); } }
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")); } }
This test checks if multiplying 4 by 5 returns 20 using the multiply method.
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); } }
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.
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.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CalcTest {
@Test
void testSum() {
int result = 2 + 3;
assertEquals(5, result);
}
}import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SampleTest {
@Test
public void testMultiply() {
int result = 3 * 4
assertEquals(12, result);
}
}Pass the test and this pattern moves unknown