Spring,SpringBoot
test 환경 분리하기, 폼 객체 mock mvc 테스트 방법
Lahezy
2023. 3. 30. 00:10
728x90
테스트 데이터 베이스와 서버 데이터 베이스 나누기
중복되는 필드가 있거나, 모든 포스트 확인 등을 테스트 하기 어려워서 분리하기로 했다.
application.properties
#테스트용 데이터 베이스와 분리
spring.profiles.default=local
application-local.properties
spring.config.activate.on-profile=local
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/cummu
spring.datasource.username={}
spring.datasource.password={}
/ ~~~~ 기존에 있던 코드들/
application-test.properties
spring.config.activate.on-profile=test
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/cummutest
spring.datasource.username={}
spring.datasource.password={}
/ ~~~~ 기존에 있던 코드들/
그리고 테스트 코드 위에 프로파일 설정을 하면 된다.
원래는 테스트인 경우 해당 위치에 리소스에. yml이나. properties를 넣으면 알아서 인메모리로(h2데이터 베이스) 동작한다는데 안 돼서 그냥 위에 처럼 했다.. (h2데이터 베이스 의존성은 gradle에서 설정해 줘야 알아서 돌아간다)
[참고]
https://devlog-wjdrbs96.tistory.com/343
https://wildeveloperetrain.tistory.com/8
https://velog.io/@stbpiza/Spring-Boot-%ED%99%98%EA%B2%BD-%EB%B6%84%EB%A6%AC%ED%95%98%EA%B8%B0
2. 테스트 서버 성공! 근데 이제 폼객체 테스트는 어떻게 하는거지
@Test
public void 유저객체생성확인() throws Exception {
//이름에 넘길 파라미터 네임
MockMultipartFile file = new MockMultipartFile("profileImg", "image.jpg", "image/jpeg", "<<jeg data>>".getBytes(StandardCharsets.UTF_8));
MemberRequestDto userMakeDto = new MemberRequestDto("password", "loginId", "nick", "bo@google.com", file);
//when
mockMvc.perform(multipart("/auth/signup") //멀티 파트로 보내고
.file(file) //파일 넣기
.param("password",userMakeDto.getPassword())
.param("loginId",userMakeDto.getLoginId())
.param("nickname",userMakeDto.getNickname())
.param("email",userMakeDto.getEmail())
)
.andExpect(status().isOk())
.andExpect(jsonPath("loginId").value("loginId"))
.andExpect(jsonPath("nickname").value("nick"))
.andExpect(jsonPath("email").value("bo@google.com"));
//then
Member find = memberService.findByNickname("nick");
assertTrue(passwordEncoder.matches("password", find.getPassword()));
assertThat(find.getLoginId()).isEqualTo("loginId");
}
위에 처럼 하면 된다.
file(file)부분에서 , MockMultipartFile("파라미터이름" ~~~) 형식으로 넣어서 테스트한다.
728x90