일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- #프로그래머스 #코딩 #자바 #왼쪽오른쪽
- 깃
- #프로그래머스 #자바 #코딩 #무작위로k개의수뽑기
- #프로그래머스 #코딩 #자바 #문자열묶기
- #프로그래머스 #코딩 #자바 #리스트자르기
- #신념 #철학 #유쾌함 #후회 #자책
- #프로그래머스
- springboot #스프링부트
- #프로그래머스 #코딩 #자바 #문자열여러번뒤집기
- #프로그래머스 #코딩 #자바 #문자열이몇번등장하는지세기
- springboot #sprinigbatch #job #step #스프링부트배치 #스프링배치
- Git
- #프로그래머스 #코딩 #자바 #수열과구간쿼리2
- #batch #스케줄러 #배치스케줄러
- 제이피에이
- #프로그래머스 #코딩 #자바 #2의영역
- #springbatch #springboot #스프링배치 #스프링부트 #배치 #joblauncher #job #step #itemreader #itemprocessor #itemwriter
- springboot #스프링부트 #junit #제이유닛 #라이프사이클 #@beforeall #@beforeeach #@afterall #@aftereach
- #springbatch #springboot #스프링배치 #스프링부트 #배치 #joblauncher #job #step #batchconfig #배치설정 #chunk
- #프로그래머스 #자바 #코딩 #배열만들기2
- @autoconfigurationmockmvc
- springboot #스프링부트 #junit #junit #제이유닛 #단위테스트코드 #테스트 #test #test
- dbeaver sqlite
- 컨트롤러테스트코드
- 코딩 #자바 #조건에맞게수열변환하기2
- springboot #@beforeall #@afterall
- #프로그래머스 #자바 #코딩 #전국대회선발
- JPA
- #프로그래머스 #코딩 #자바 #수열과구간쿼리3
- springboot #스프링투브
- Today
- Total
David의 블로그
[JUnit]JUnit으로 Controller 테스트 코드 만들기 본문
현재 인천 쪽 프로젝트에 참여 중인데, 썰을 좀 풀어보려고 한다.
팀에 AA담당자분이 본격적으로 개발에 착수하기 전 AA코드를 미리 맛보는 시간을 가졌었다.
이런 적은 처음이라 설레고 기대가됐다. 내가 어느정도 AA에 관심을 가지는 계기가 됐다고 생각한다.
담당자분은 단위 테스트 코드 작성을 강조하셨다.
예전에 이직/채용 사이트에서 JUnit처럼 단위 테스트 프레임워크 경험을 물어본 몇몇 회사가 기억났다.
이참에 공부해서 알아놓으면 이직에 도움이 되지 않을까 싶었다.
서론이 길었다. 지금 시작하겠다.
[MyAccountApplicationTests.java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
package com.example.demo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@SpringBootTest // 테스트용 애플리케이션 컨텍스트 생성
@AutoConfigureMockMvc // MockMvc 생성 및 자동 구성
class MyAccountApplicationTests {
@Autowired
protected MockMvc mockMvc;
@Autowired
private WebApplicationContext context; // 자신의 스프링부트의 컨트롤러, 빈, 핸들러 매핑, 뷰리졸버 등 정보가 담김.
@BeforeEach
public void mockMvcSetup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); // MockMvc 객체를 만들어주는 구문임.
}
// @Test
// void contextLoads() {
// }
@DisplayName("BaseController의 /index.do에 요청한다.")
@Test
public void httpIndex() throws Exception {
// given
String url = "/index.do";
// when
final ResultActions result = mockMvc.perform(get(url).accept(MediaType.APPLICATION_JSON));
// then
result
.andExpect(status().isOk())
.andExpect(view().name("/loginForm"));
// .andExpect(model().attributeExists("showYearList"));
}
}
|
cs |
20번 : @SpringBootApplication이 선언된 클래스를 찾고, 그 클래스에 포함돼있는
Bean을 찾은 다음 테스트용 애플리케이션 컨텍스트라는 것을 만든다.
21번 : MockMvc를 생성하고 자동으로 구성하는 어노테이션. MockMvc는 서버에 배포하지 않아도 테스트용 MVC 환경을
만들어 요청 및 전송, 응답 기능을 제공하는 유틸리티 클래스다. 즉, Controller 테스트할 때 쓰인다.
28번 : 자신의 스프링부트 프로젝트 Controller, Bean, Handler 매핑 등 정보가 들어있다.
30 ~ 32번 : MockMvc객체를 만들어주는 구문이다.
45번 : perform() 메소드는 요청을 전송하는 메소드다. 결과로 ResultActions 객체를 받는데,
반환값을 검증하고 확인하는 andExpect()메소드를 제공한다.
45번 : accept() 메소드는 요청을 하고 어떤 타입으로 응답을 받을지 정하는 메소드. XML, JSON 등 여러 타입이 존재하는데, 여기서는 JSON으로 설정했다.
48번 : andExpect() 메소든 앞서 말했던 것처럼 반환값을 검증하고 확인하는 메소드다.
[HTTP 주요 응답 코드]
48번 처럼 응답 코드를 isOk() (200) 메소드를 사용했고, 이외에 여러 응답 코드가 다른 메소드들이 존재한다.
그리고
48번, 49번 처럼 응답 코드나 view 이름 값을 검증하려면 status()와 view()를 쓰고 import를 받으면 되겠다.
[결과]
결과 이상 무! 끝!!
'프로그래밍 > Spring Boot' 카테고리의 다른 글
[Spring Boot] JPA 커스텀 쿼리 메소드에 @Transactional 붙이기 (2) | 2025.05.22 |
---|---|
[Spring Boot] Spring Boot에 SQLite3 연동하기 (0) | 2025.05.10 |
[JUnit] @AfterAll @BeforeAll메소드 사용할 때 주의점. (4) | 2025.05.05 |
[JUnit] JUnit 테스트 코드 라이프 사이클 (2) | 2025.05.02 |
[JUnit] 자바 언어를 위한 단위 테스트 프레임워크 JUnit (2) | 2025.05.02 |