본문 바로가기
  • 🕊️ A Piece of Peace
🖥️ PC/스프링

5. 4장 스프링부트3 와 테스트

by Moom2n 2024. 8. 6.

* 이 책은 골든래빗의 <스프링 부트 3 백엔드 개발자 되기>(2판)을 읽고 쓴 TIL입니다.

https://vo.la/JSanO

 

스프링 부트 3 백엔드 개발자 되기: 자바 편 : 네이버 도서

네이버 도서 상세정보를 제공합니다.

search.shopping.naver.com

 

given-when-then 패턴 : 테스트 실행 준비 -> 테스트 진행 -> 테스트 결과 검증

 

JUnit : 단위 테스트 프레임워크

Spring Test, Spring Boot Test : 스프링 부트 애플리케이션을 위한 통합 테스트 지원

AssertJ : 검증문 작성 사용 라이브러리

Mockito : 테스트에 사용할 가짜 객체인 목 객체를 관리하고, 검증할 수 있게 지원하는 프레임워크

JSONassert, JsonPath

 

AssertJ 적용

 

String name1 = "홍길동";
String name2 = "홍길동";
String name3 = "홍길은";

assertThat(name1).isNotNull();
assertThat(name2).isNotNull();
assertThat(name3).isNotNull();

assertThat(name1).isEqualTo(name2);

assertThat(name1).isNotEqualTo(name3);

--------

int number1 = 15;
int number2 = 0;
int number3 = -5;

assertThat(number1).isPositive();
assertThat(number2).isZero();
assertThat(number3).isNegative();

assertThat(number1).isGreaterThan(number2);

assertThat(number3).isLessThan(number2);

 

@SpringBootTest	// @SpringBootApplication 이 있는 클래스를 찾고 그 클래스에 포함되어 있는 빈을 찾은 다음 테스트용 애플리케이션 컨텍스트 생성
@AutoConfigureMockMvc // 애플리케이션을 서버에 배포하지 않고도 테스트용 MVC 환경 생성. 요청 및 전송, 응답 기능 제공
class TestControllerTest {
	@Autowired
	protected MockMvc mockMvc;

	@Autowired
	private WebApplicationContext context;

	@Autowired
	private MemberRespository memberRepository;

	@BeforeEach
	public void mockMvcSetUp() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@AfterEach
	public void cleanUp() {
		memberRepository.deleteAll();
	}

	@DisplayName("getAllMembers : 아티클 조회에 성공")
	@Test
	public void getAllMembers() throws Exception {
		// given
		final String url = "/test";
		Member savedMember = memberRepository.save(new Member(1L, "홍길동"));

		// when
		final ResultActions result = mockMvc.perform(get(url).accept(MediaType.APPLICATION_JSON));

		// then
		result
			.andExpect(status().isOk())
			.andExpect(jsonPath("$[0].id").value(savedMember.getId()))
			.andExpect(jsonPath("$[0].name").value(savedMember.getName()));
	}
}

 

@RestController
public class QuizController {

	@GetMapping("/quiz")
	public ResponseEntity<String> quiz(@RequestParam("code") int code) {
		switch (code) {
			case 1:
				return ResponseEntity.created(null).body("Created!");
			case 2:
				return ResponseEntity.ok().body("Bad Request!");
			default:
				return ResponseEntity.ok().body("OK!");
		}
	}

	@PostMapping("/quiz")
	public ResponseEntity<String> quiz2(@RequestBody Code code) {
		switch (code.value()) {
			case 1:
				return ResponseEntity.status(403).body("Forbidden!");
			default:
				return ResponseEntity.ok().body("OK!");
		}
	}

	record Code(int value) {}
}


--------


@SpringBootTest
@AutoConfigureMockMvc
class QuizControllerTest {

	@Autowired
	protected MockMvc mockMvc;

	@Autowired
	private WebApplicationContext context;

	@Autowired
	private ObjectMapper objectMapper;

	@BeforeEach
	public void mockMvcSetUp() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@DisplayName("quiz(): GET /quiz?code=1 이면 응답 코드는 201, 응답 본문은 Created!")
	@Test
	public void getQuiz1() throws Exception {
		// given
		final String url = "/quiz";

		// when
		final ResultActions result = mockMvc.perform(get(url).param("code", "1"));

		// then
		result
			.andExpect(status().isCreated())
			.andExpect(content().string("Created!"));
	}

	@DisplayName("quiz(): GET /quiz?code=2 이면 응답 코드는 400, 응답 본문은 Bad Request!")
	@Test
	public void getQuiz2() throws Exception {
		// given
		final String url = "/quiz";

		// when
		final ResultActions result = mockMvc.perform(get(url).param("code", "2"));

		// then
		result
			.andExpect(status().isBadRequest())
			.andExpect(content().string("Bad Request!"));
	}

	@DisplayName("quiz(): POST /quiz?code=1 이면 응답 코드는 403, 응답 본문은 Forbidden!")
	@Test
	public void postQuiz1() throws Exception {
		// given
		final String url = "/quiz";

		// when
		final ResultActions result = mockMvc.perform(post(url)
			.contentType(MediaType.APPLICATION_JSON)
			.content(objectMapper.writeValueAsString(new QuizController.Code(1))));

		// then
		result
			.andExpect(status().isForbidden())
			.andExpect(content().string("Forbidden!"));
	}

	@DisplayName("quiz(): POST /quiz?code=13 이면 응답 코드는 200, 응답 본문은 OK!")
	@Test
	public void postQuiz13() throws Exception {
		// given
		final String url = "/quiz";

		// when
		final ResultActions result = mockMvc.perform(post(url)
			.contentType(MediaType.APPLICATION_JSON)
			.content(objectMapper.writeValueAsString(new QuizController.Code(13))));

		// then
		result
			.andExpect(status().isOk())
			.andExpect(content().string("OK!"));
	}
}

 

ObjectMapper : 클래스와 JSON 간 변환 처리. (객체 직렬화)

 

 

'🖥️ PC > 스프링' 카테고리의 다른 글

6. 5장 데이터베이스 조작이 편해지는 ORM  (0) 2024.08.07
4. 3장 스프링부트3 구조 이해하기  (0) 2024.08.01
3. 2장  (0) 2024.07.31
2. 1장  (0) 2024.07.30
1. 스프링부트3 백엔드  (0) 2024.07.30