Introduction
JUnit tests help check if your code works correctly. They catch mistakes early so you can fix them fast.
JUnit tests help check if your code works correctly. They catch mistakes early so you can fix them fast.
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.
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); } }
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()); } }
This test checks if 4 times 5 equals 20. If yes, the test passes.
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); } }
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.
JUnit tests check if code works as expected.
Use @Test to mark test methods.
Assertions compare expected and actual results.
@Test?@Test annotation@Test annotation marks a method as a test method in JUnit, meaning it will be run to check code behavior.@Test marks test methods [OK]@Test annotation to mark a method as a test.assertEquals(expected, actual). @Test public void testMethod() { assertEquals(5, 2 + 3); } matches this.import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class SampleTest {
@Test
void additionTest() {
assertEquals(10, 5 + 5);
}
}import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalcTest {
@Test
public void testSum() {
int result = 2 + 2;
assertEquals(5, result);
}
}multiply(int a, int b) returns 0 when one input is 0. Which test method is correct?@Test and return void. @Test public void testMultiplyZero() { assertEquals(0, multiply(0, 5)); } meets this.assertEquals(0, multiply(0, 5)), which is correct.Pass the test and this pattern moves unknown