Project

댓글 test 코드

haedal-uni 2022. 6. 20. 18:36
728x90

CommentController

더보기
@RequiredArgsConstructor
@RestController
public class CommentController {
    private final CommentService commentService;

    // 댓글 저장
    @PostMapping("/comment")
    public Comment setComment(@ModelAttribute CommentDto commentDto) {
        return commentService.setComment(commentDto);
    }

    @GetMapping("/comment")
    public List<Comment> getComment(@RequestParam int idx){
        return commentService.getComment(idx);
    }

    // AuthenticationPrincipal : 로그인한 사용자의 정보를 파라메터로 받고 싶을때
    @PutMapping("/comment/{commentId}/registry/{registryId}")
    public Comment updateComment(@PathVariable Long commentId, @PathVariable int registryId,
                                 @RequestBody CommentDto commentDto,
                                 @AuthenticationPrincipal UserDetailsImpl userDetails) throws AccessDeniedException {
        return commentService.updateComment(commentId, registryId, commentDto, userDetails);
    }

    @GetMapping("/finduser")  // sessionStorage에 닉네임 값이 저장 안되어 있는 경우
    public String findUser(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        return commentService.findUser(userDetails);
    }
}

 

 

Comment

더보기
@Setter
@Getter
@NoArgsConstructor
@Entity
public class Comment extends Timestamped {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    @Column(name = "COMMENT_ID")
    private Long idx;

    @Column(nullable = true)
    private String nickname;

    @Column(nullable = true)
    private String comment;

    @Column(nullable = true)
    private int registryId;

    public Comment(CommentDto commentDto) {
        this.nickname = commentDto.getNickname();
        this.comment = commentDto.getComment();
        this.registryId = commentDto.getRegistryId();
    }
}

 

 

CommentDto

더보기
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class CommentDto {
    private String nickname;
    private String comment;
    private int registryId;
}

* Dto에 @NoArgsConstructor, @AllArgsConstructor 추가

2022.06.22 - [TIL] - 280일차(모험 189일차) - 댓글 수정(PUT)

 

 

 

CommentRepository

public interface CommentRepository extends JpaRepository<Comment, Long> {
    List<Comment> findAllByRegistryId(int idx);
}

 

 

CommentService

더보기
@RequiredArgsConstructor
@Service
public class CommentService {
    private final CommentRepository commentRepository;
    private final RegistryRepository registryRepository;

    @Transactional
    public Comment setComment(CommentDto commentDto) {
        Comment comment = new Comment(commentDto);
        commentRepository.save(comment);
        return comment;
    }

    public List<Comment> getComment(int idx){
        List<Comment> commentList = commentRepository.findAllByRegistryId(idx);
        return commentList;
    }

    public Comment updateComment(Long commentId, int registryId, CommentDto commentDto, UserDetailsImpl userDetails) throws AccessDeniedException {
        registryRepository.findById((long) registryId).orElseThrow(
                () -> new NullPointerException("해당 게시글이 존재하지 않습니다.")
        );

        Comment comment = commentRepository.findById(commentId).orElseThrow(
                () -> new NullPointerException("해당 댓글이 존재하지 않습니다.")
        );

        if (!userDetails.getUser().getNickname().equals(comment.getNickname()) ) {
            throw new AccessDeniedException("권한이 없습니다.");
        }

        comment.setComment(commentDto.getComment());
        commentRepository.save(comment);
        return comment;

    }

    // sessionStorage에 닉네임 값이 저장 안되어 있는 경우
    public String findUser(UserDetailsImpl userDetails) {
        return userDetails.getUser().getNickname();
    }

}

 

 

CommentServiceTest

더보기
package com.dalcho.adme.service;

import com.dalcho.adme.domain.Comment;
import com.dalcho.adme.domain.Registry;
import com.dalcho.adme.domain.User;
import com.dalcho.adme.dto.CommentDto;
import com.dalcho.adme.dto.RegistryDto;
import com.dalcho.adme.dto.SignupRequestDto;
import com.dalcho.adme.repository.CommentRepository;
import com.dalcho.adme.repository.RegistryRepository;
import com.dalcho.adme.security.UserDetailsImpl;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

import static org.springframework.test.util.AssertionErrors.assertEquals;

@DisplayName("H2를 이용한 Comment TEST")
@TestPropertySource(locations = "/application.properties")
@ExtendWith( SpringExtension. class )
@SpringBootTest( webEnvironment = SpringBootTest . WebEnvironment . RANDOM_PORT )
@Transactional
public class CommentServiceTest {
    @Autowired CommentService commentService;
    @Autowired CommentRepository commentRepository;
    @Autowired RegistryService registryService;
    @Autowired UserService userService;
    @Autowired RegistryRepository registryRepository;

    UserDetailsImpl nowUser;
    CommentDto commentDto;
    Registry registry;

    @Test
    @DisplayName("beforeEach 작성 전에 작성한 post test")
    void save1Comment() throws IOException {
        //given
        CommentDto comment = new CommentDto();
        comment.setComment("funfun");
        comment.setNickname("hh");
        comment.setRegistryId(1);

        //when
        Comment saveComment = commentService.setComment(comment);

        //then
        Assertions.assertThat(comment.getComment()).isEqualTo(saveComment.getComment());
        Assertions.assertThat(comment.getNickname()).isEqualTo(saveComment.getNickname());
        Assertions.assertThat(comment.getRegistryId()).isEqualTo(saveComment.getRegistryId());
    }


    @BeforeEach
    void beforeEach() {
        SignupRequestDto userDto = new SignupRequestDto("test1", "test1", "d","d","d");
        User user = userService.registerUser(userDto);
        this.nowUser = new UserDetailsImpl(user);

        RegistryDto registryDto = new RegistryDto("닉네임","타이틀","본문");

        Registry saveRegistry = new Registry(registryDto);
        this.registry = registryRepository.save(saveRegistry);

        this.commentDto = new CommentDto();
        int registryIdx = Math.toIntExact(registry.getIdx());
        this.commentDto.setComment("comment");
        this.commentDto.setNickname(nowUser.getUsername());
        this.commentDto.setRegistryId(registryIdx);
    }


    @Test
    void saveComment() throws IOException {
        // given

        // when
        Comment comment = commentService.setComment(commentDto);

        // then
        Comment commentTest = commentRepository.findById(comment.getIdx()).orElseThrow(
                () -> new NullPointerException("comment 생성 x")
        );

        assertEquals("comment의 id값이 일치하는지 확인", comment.getIdx(), commentTest.getIdx());
    }




    @Test
    @DisplayName("comment 수정")
    void updateComment() throws IOException {

        int registryIdx = Math.toIntExact(registry.getIdx());
        Comment comment = commentService.setComment(commentDto);

        CommentDto commentDtoEdit = new CommentDto();
        commentDto.setComment("comment-edit");


        //when
        Comment commentTest = commentService.updateComment(comment.getIdx(), registryIdx, commentDtoEdit, nowUser);

        //then
        assertEquals("Comment Id 값이 일치하는지 확인.", comment.getIdx(), commentTest.getIdx());
        assertEquals("Comment 내용이 업데이트 되었는지 확인", commentDtoEdit.getComment(), commentTest.getComment());
    }



    @Test
    @DisplayName("comment 삭제 성공")
    void deleteComment() throws IOException {
        // given
        Comment comment = commentService.setComment(commentDto);

        //when
        int registryIdx = Math.toIntExact(registry.getIdx());
        commentService.deleteComment(comment.getIdx(), registryIdx, commentDto, nowUser);

        // then
        Optional<Comment> commentTest = commentRepository.findById(comment.getIdx());
        if (commentTest.isPresent())
            throw new IllegalArgumentException("Comment 가 정상적으로 삭제되지 않았습니다.");
        else
            assertEquals("Comment 가 비어있다.", Optional.empty(), commentTest);
    }
}

 

 

 

 

@DisplayName("H2를 이용한 Comment TEST")
@TestPropertySource(locations = "/application.properties")
@ExtendWith( SpringExtension. class )
@SpringBootTest( webEnvironment = SpringBootTest . WebEnvironment . RANDOM_PORT )
@Transactional
public class CommentServiceTest {
    @Autowired
    CommentService commentService;
    @Autowired RegistryService registryService;
    @Autowired RegistryRepository registryRepository;
    @Autowired CommentRepository commentRepository;


    @Test
    @DisplayName("db 저장")
    void saveComment() throws IOException {
        //given
        CommentDto comment = new CommentDto();
        comment.setComment("funfun");
        comment.setNickname("hh");
        comment.setRegistryId(1);

        //when
        Comment saveComment = commentService.setComment(comment);

        //then
        Assertions.assertThat(comment.getComment()).isEqualTo(saveComment.getComment());
        Assertions.assertThat(comment.getNickname()).isEqualTo(saveComment.getNickname());
        Assertions.assertThat(comment.getRegistryId()).isEqualTo(saveComment.getRegistryId());
    }



    @Test
    @DisplayName("id가 1인 댓글")
    void showComment() throws IOException {
        //given
        RegistryDto registry = new RegistryDto();
        registry.setTitle("첫 번째");
        registry.setMain("1");
        registry.setNickname("nickname");

        CommentDto comment = new CommentDto();
        comment.setComment("funfun");
        comment.setNickname("hh");
        comment.setRegistryId(1);

        CommentDto comment1 = new CommentDto();
        comment1.setComment("wow");
        comment1.setNickname("hh");
        comment1.setRegistryId(1);

        //when
        Registry saveRegistry = registryService.setUpload(registry);
        Comment saveComment = commentService.setComment(comment);
        Comment saveComment1 = commentService.setComment(comment1);

        //then
        int idx = Math.toIntExact(saveRegistry.getIdx()); // long을 int로 형변환
        List<Comment> results = commentRepository.findAllByRegistryId(idx);
        Assertions.assertThat(saveComment.getComment()).isEqualTo(results.get(0).getComment());
        Assertions.assertThat(saveComment1.getComment()).isEqualTo(results.get(1).getComment());
    }
}

 

 

728x90

'Project' 카테고리의 다른 글

댓글 crud 코드  (0) 2022.06.26
회원가입 코드  (0) 2022.06.19
로그인 코드  (0) 2022.06.18
웹소켓 - 상대방과 나 구분하기  (0) 2022.06.04
웹소켓 기본 코드  (0) 2022.06.03