82일 차 - 스프링 통합 테스트, 트랜잭션 (23.04.25)

yvonne·2023년 4월 25일
0

📂Spring

목록 보기
14/18
post-thumbnail

📝 통합 테스트 (컨트롤러 테스트)

🔎 MockMvc 테스트

✔ HomeControllerTest.java

package edu.global.ex.controller;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
@AutoConfigureMockMvc // 웹 어플리케이션에서 컨트롤러를 테스트할 때, 서블릿 컨테이너를 모킹하기 위해 필요
class HomeControllerTest {

	@Autowired
	private MockMvc mockMvc; // 웹 브라우저 대용

	// @GetMapping("/") 테스트
	@Disabled
	@Test
	void testHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
		.andExpect(MockMvcResultMatchers.status().isOk())
		.andDo(print());
	}

	@Test
	void testUserHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/user/userHome"))
		.andExpect(MockMvcResultMatchers.status().isOk())
		.andDo(print());
	}
}
  • 결과 : 오류 발생

✔ 코드 추가

@WithMockUser(username = "user",password = "user", roles = "USER")
  • @WithMockUser 추가하여 오류 해결 (권한 설정)





2. 트랜잭션

📌 트랜잭션의 의미

  • 일련의 작업 단위

  • 완전히 처리되거나 All-OR-Nothing

📌 소프트웨어에서의 트랜잭션 처리

  • 기본적으로(전통적으로) 하나의 함수에 묶어서 처리함

  • 스프링의 경우 그 기준은 비지니스 로직을 처리하는 Service 단에서의 함수로 묶어버림

📌 스프링에서는 기본적으로 함수,클래스,인터페이스 위에 @Transactional로 롤백처리

  • Service단에서 트랜잭션의 단위를 나타내는 @Transactional 애너테이션을 함수,클래스,인터페이스 위에 붙이면 DB에서의 ROLLBACK 역할을 한다.

  • ROLLBACK(트랜잭션)은 해당 함수에서 에러, 예외가 일어났을 때 실행된다.

profile
개발 연습장

0개의 댓글