테스트(JUnit, Mockito, Spring Boot)

Yuno·2024년 8월 11일

JavaSpring

목록 보기
13/16

❗️테스트는

소프트웨어 개발에서 중요한 과정으로, 코드를 검증하고 버그를 찾아내는 역할을 함.


📌 JUnit

Java 프로그래밍 언어를 위한 단위 테스트 프레임워크.
테스트 케이스를 작성하고 실행하는 데 사용됨

  • 테스트 클래스 : @Test 어노테이션이 붙은 메서드를 포함하는 클래스
  • 테스트 메서드 : @Test 어노테이션을 붙여 테스트할 메서드를 정의
  • Assertions : 테스트의 성공 여부를 판단하는 메서드들을 제공.
    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");
    }
}

📌 Mockito

Java 객체의 목(mock) 객체를 생성하고 사용하기 위한 프레임워크.
주로 의존성 주입을 사용하여 외부 종속성을 가짜로 대체하여 테스트

  • Mock : 실제 객체의 동작을 모방하는 객체
  • Stub : 메서드 호출에 대해 정의된 응답을 제공
  • Verification : 메서드 호출이 특정 횟수만큼 발생했는지 검증
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 테스트

Spring Boot는 강력한 테스트 지원 기능을 제공함.
애플리케이션의 다양한 구성 요소를 테스트할 수 있도록 도와줌.

  • @SpringBootTest : 전체 애플리케이션 컨텍스트를 로드하여 통합 테스트를 수행
  • @WebMvcTest : MVC 컨트롤러만을 로드하여 웹 계층의 테스트를 수행
  • @DataJpaTest : JPA 관련 컴포넌트만 로드하여 데이터베이스 관련 테스트를 수행
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\"}"));
    }
}

💻요약

  • JUnit : Java 애플리케이션의 단위 테스트를 위한 프레임워크
  • Mockito : Java 객체의 목(mock) 객체를 생성하여 테스트하는 데 사용됨
  • Spring Boot 테스트 : Spring Boot 애플리케이션의 다양한 구성 요소를 테스트할 수 있도록 도와주는 기능을 제공
profile
Hello World

0개의 댓글