Java에서 독립된 단위테스트 (Unit test)를 지원해주는 프레임워크를 말한다.
package kr.ac.green.test;
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import kr.ac.green.Car;
import kr.ac.green.CarManager;
import kr.ac.green.GetByPriceException;
public class TestCarManager {
private static CarManager manager;
private Connection con;
//전체 테스트 시작전 한번
@BeforeAll
public static void setUpBeforeClass() throws Exception {
manager = CarManager.getInstance();
}
//전체 테스트 종료 후 한번
@AfterAll
public static void tearDownAfterClass() throws Exception {
}
//매 테스트 전에 호출
@BeforeEach
public void setUp() throws Exception {
con = manager.connect();
//setAutoCommit : 내가 커밋하기 전까지 할지 안할지 결정
//false : 내가 직접 넣기 전까지 하지마라
con.setAutoCommit(false);
}
//매 테스트 후에 호출
@AfterEach
public void tearDown() throws Exception {
//내가 원하는 대로 안되면 rollback하기
con.rollback();
manager.disconnect(con);
}
//테스트 메소드
@Test
public void testInsertCar() {
Car car = new Car("spark", 1800, "so cool");
try {
int result =manager.insertCar(con, car);
//첫번째 파라미터가 기대하는 값이다.
Assert.assertEquals(1, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testDeleteCar() {
Car car = new Car(15);
try {
int result = manager.deleteCar(con,car);
Assert.assertEquals(1, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testUpdateCar() {
Car car = new Car(28, "equus", 15000, "super good");
try {
int result = manager.update(con, car);
Assert.assertEquals(1, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testGetAll() {
try {
Car[] arr = manager.getAll(con);
Assert.assertEquals(9, arr.length);
}catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testGetCarByPrice() {
try {
Assert.assertEquals(7, manager.getCarByPrice(con, 2000, 4000).length);
}catch (GetByPriceException e) {
e.printStackTrace();
}
}
}
→ 위는 JUnit5 버전이고, JUnit4 버전의 메소드들이 하는 일도 위와 같다.
→ 위 코드의 주석을 보고 이해하면 된다.
순서
: BeforeClass → Before → Test → After → AfterClass 이다.