2024.02.18
[테킷 백엔드] 프로젝트 - alcoholfriday
환경 - 스프링부트 3.2.1, 자바 JDK17
작업 - 장바구니에 상품 추가, 조회 테스트
@WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
import org.springframework.security.test.context.support.WithSecurityContext;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithAccountSecurityContextFactory.class)
public @interface WithAccount {
String email() default "test@example.com";
}
import com.drunkenlion.alcoholfriday.domain.auth.enumerated.ProviderType;
import com.drunkenlion.alcoholfriday.domain.member.dao.MemberRepository;
import com.drunkenlion.alcoholfriday.domain.member.entity.Member;
import com.drunkenlion.alcoholfriday.domain.member.enumerated.MemberRole;
import com.drunkenlion.alcoholfriday.global.security.auth.UserDetailsServiceImpl;
import com.drunkenlion.alcoholfriday.global.security.auth.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import java.time.LocalDateTime;
public class WithAccountSecurityContextFactory implements WithSecurityContextFactory<WithAccount> {
@Autowired
MemberRepository memberRepository;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
public SecurityContext createSecurityContext(WithAccount annotation) {
Member member = Member.builder()
.email(annotation.email())
.provider(ProviderType.KAKAO)
.name("테스트")
.nickname("test")
.role(MemberRole.MEMBER)
.phone(1012345678L)
.certifyAt(null)
.agreedToServiceUse(true)
.agreedToServicePolicy(true)
.agreedToServicePolicyUse(true)
.createdAt(LocalDateTime.now())
.updatedAt(null)
.deletedAt(null)
.build();
memberRepository.save(member);
UserPrincipal userPrincipal = UserPrincipal.create(member);
Authentication authentication =
new UsernamePasswordAuthenticationToken(
userPrincipal, null, userPrincipal.getAuthorities()
);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}
@PostMapping
public ResponseEntity<CartResponse> addCartList(@RequestBody CartReqList cartReqList, @AuthenticationPrincipal UserPrincipal userPrincipal) {
CartResponse cartResponse = cartService.addCartList(cartReqList.getCartRequestList(), userPrincipal.getMember());
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(cartResponse.getCartId())
.toUri();
return ResponseEntity.created(location).body(cartResponse);
}
@Test
@DisplayName("장바구니에 한 개 상품 등록")
@WithAccount
void addCartOneItem() throws Exception {
// when
ResultActions resultActions = mvc
.perform(post("/v1/carts")
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content("""
{
"cartRequestList": [
{
"itemId": "%d",
"quantity": "2"
}
]
}
""".formatted(itemId))
)
.andDo(print());
// then
resultActions
.andExpect(status().isCreated())
.andExpect(handler().handlerType(CartController.class))
.andExpect(handler().methodName("addCartList"))
.andExpect(jsonPath("$", instanceOf(LinkedHashMap.class)))
.andExpect(jsonPath("$.cartId", instanceOf(Number.class)))
.andExpect(jsonPath("$.cartDetailResponseList[0].item.id", instanceOf(Number.class)))
.andExpect(jsonPath("$.cartDetailResponseList[0].quantity", notNullValue()));
}