스프링
스프링 시큐리티가 있는 프로젝트에서 WebMvcTest를 사용해서 컨트롤러테스트할때 시큐리티 끄기
rkrkrr0101
2024. 2. 3. 20:17
일단 @WebMvcTest를 사용하면 무조건 시큐리티빈을 가져오게됨,이건 컨트롤할수없음
그래서 할수있는건,테스트쪽에 시큐리티컨피그 클래스를 모킹해서 만들고,그걸 가져오는방식임
먼저 아무것도 하지않는 시큐리티컨피그를 만들고
package com.shop.shop.mock
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.web.SecurityFilterChain
@EnableWebSecurity
class MockSecurityConfig {
@Bean
fun filterChain(http: HttpSecurity):SecurityFilterChain{
http.csrf {
it.disable()
}
return http.build()
}
}
@ImportAutoConfiguration을 사용해서 모킹 시큐리티컨피그파일을 등록하면됨
package com.shop.shop.member.controller
import com.shop.shop.member.domain.Member
import com.shop.shop.member.service.MemberService
import com.shop.shop.mock.MockSecurityConfig
import com.shop.shop.security.SecurityConfig
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.BDDMockito.given
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.ImportAutoConfiguration
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.FilterType
import org.springframework.context.annotation.Import
import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@WebMvcTest( MemberController::class)
@MockBean(JpaMetamodelMappingContext::class)
@ImportAutoConfiguration(MockSecurityConfig::class)
class MemberControllerTest (
@Autowired val mvc:MockMvc,
@MockBean @Autowired val memberService: MemberService,
){
@Test
fun 정상적으로_회원가입을_할수있다(){
val member = Member("username111", "password111", "name111", "qqq@aqw.com")
given(memberService.isUser(member))
.willReturn(false)
mvc.perform(post("/join"))
.andExpect(status().isOk)
}
}