@BeforeEach 사용예시.

yesrin·2023년 8월 1일

Spring

목록 보기
12/18
@SpringBootTest
@ExtendWith(MockitoExtension.class) //@Mock 사용을 위해 선언
class PostSeriveTest {
    private Principal mockPrincipal;
    @Autowired
    PostRepository postRepository;
    @Autowired
    UserDetailsImpl userDetails;
    @Autowired
    UserRepository userRepository;
    @Autowired
    MessageSource messageSource;

    User testUser;
    
@BeforeEach
    private void mockUserSetup() {
        // Mock 테스트 유져 생성
        String username = "sollertia4351";
        String password = "robbie1234";
        UserRoleEnum role = UserRoleEnum.USER;
        testUser = new User(username, password, role);
        UserDetailsImpl testUserDetails = new UserDetailsImpl(testUser);
        mockPrincipal = new UsernamePasswordAuthenticationToken(testUserDetails, "", testUserDetails.getAuthorities());
    }
    
@Test
    @DisplayName("게시글 업데이트")
    void updatePost() {
        //given
        Long postId = 3L;
        String title = "Test title";
        String contents = "Test content";

        PostRequestDto requestDto = new PostRequestDto(title, contents);
        requestDto.setTitle(title);
        requestDto.setContents(contents);

        Post post = new Post(requestDto, testUser);
        PostServiceImpl postService = new PostServiceImpl(postRepository, messageSource);

        given(postRepository.findById(postId)).willReturn(Optional.of(post));

        //when 실제로 수행
        PostResponseDto result = postService.updatePost(postId, requestDto, testUser);

        //then
        assertEquals(title, result.getTitle());
        assertEquals(contents, result.getContents());
    }
    }
profile
안녕하세요! 틀린 정보는 댓글 달아 주세요.

0개의 댓글