Skip to content

Commit

Permalink
feat: 컨트롤러 레이어 테스트를 위한 설정 미리 추가 (#72) (KAN-129)
Browse files Browse the repository at this point in the history
  • Loading branch information
ywonchae1 committed Nov 3, 2024
1 parent ceb19f3 commit 13bb28e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.ioteatime.meonghanyangserver.config.mock;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.test.context.support.WithSecurityContext;

@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithCustomMockUserSecurityContextFactory.class)
public @interface WithCustomMockUser {
String userId() default "1";

String email() default "[email protected]";

String username() default "test";

String password() default "testpassword";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.ioteatime.meonghanyangserver.config.mock;

import org.ioteatime.meonghanyangserver.user.domain.UserEntity;
import org.ioteatime.meonghanyangserver.user.dto.CustomUserDetail;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;

public class WithCustomMockUserSecurityContextFactory
implements WithSecurityContextFactory<WithCustomMockUser> {
@Override
public SecurityContext createSecurityContext(WithCustomMockUser annotation) {
String userId = annotation.userId();

UserEntity user = UserEntity.builder().id(Long.parseLong(userId)).build();
CustomUserDetail customUserDetail = new CustomUserDetail(user);

UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(
customUserDetail, null, customUserDetail.getAuthorities());
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(token);
return context;
}
}

0 comments on commit 13bb28e

Please sign in to comment.