소프트웨어 개발에서 중요한 과정으로, 코드를 검증하고 버그를 찾아내는 역할을 함.
Java 프로그래밍 언어를 위한 단위 테스트 프레임워크.
테스트 케이스를 작성하고 실행하는 데 사용됨
@Test 어노테이션이 붙은 메서드를 포함하는 클래스@Test 어노테이션을 붙여 테스트할 메서드를 정의assertEquals(expected, actual)import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MathUilsTest {
@Test
public void testAdd() {
MathUtils mathUtils = new MathUtils();
int result = mathUtils.add(2, 3);
assertEquals(5, result, "2 + 3 should equal 5");
}
}
Java 객체의 목(mock) 객체를 생성하고 사용하기 위한 프레임워크.
주로 의존성 주입을 사용하여 외부 종속성을 가짜로 대체하여 테스트
import static org.mockito.Mockito.*;
public class ServiceTest {
@Test
public void testService() {
// Mock 객체 생성
MyRepository mockRepository = mock(MyRepository.class);
// Stub 설정
When(mockRepository.findById(1)).thenReturn(new Item("item1"));
// 테스트할 서비스
MyService service = new MyService(mockRepository);
// 메서드 호출
Item item = service.getItemById(1);
// 검증
assertEquals("item1", item.getName());
verify(mockRepository).findById(1);
}
}
Spring Boot는 강력한 테스트 지원 기능을 제공함.
애플리케이션의 다양한 구성 요소를 테스트할 수 있도록 도와줌.
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGet() throws Exception {
mockMvc.perform(get("/api/items/1"))
.andExpect(status().isOk())
.andExpect(content().json("{\"id\":1, \"name\":\"item1\"}"));
}
}