JUnit ek open-source testing framework hai jo Java programs ke liye unit testing support karta hai. Iska use test-driven development (TDD) me hota hai jisme code likhne se pehle tests likhe jate hain.
JUnit me test likhne ke liye ek class create karte hain jisme test methods ko @Test annotation diya jata hai:
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(5, 3);
assertEquals(8, result);
}
}
Is example me testAdd method Calculator class ke add method ko test kar raha hai.
@Test: Test method ko mark karta hai.@Before: Har test ke pehle run hota hai, setup ke liye.@After: Har test ke baad run hota hai, cleanup ke liye.@BeforeClass: Test class ke start me ek baar run hota hai.@AfterClass: Test class ke end me ek baar run hota hai.@Ignore: Kisi test ko temporarily disable karta hai.