이전에 이어서 service랑 controller를 작성을 전부 완료하였고 테스트도 완료하였습니다.
내일은 프론트단을 완료하고 현재  pc내에서 웹 작동해볼 예정이고 운영웹에는 테스트 조금더 한후에 적용할 예정입니다. 코드 관련해서 조금 공부할 필요가 있다고 생각했고요. 그건 내일 작성하도록 하겠습니다.
2023.10.09 - [웹/Spring vue 웹 개발] - spring vue 댓글 01

spring vue 댓글 01

2023.10.08 - [웹/Spring vue 웹 개발] - [리팩토링]게시판완료 (프론트단 및 백단 연결 변경 완료) [리팩토링]게시판완료 (프론트단 및 백단 연결 변경 완료)2023.10.02 - [웹/Spring vue 웹 개발] - [리팩토링]게

kwaksh2319.tistory.com

서비스:
CommentService

public interface CommentService {
    Comment save(Comment comment);
    List<Comment> findAll();
    Optional<Comment> findById(Long id);
    Comment update(Long id,Comment saveComment);
    void deleteAll();
}

CommentSerivceImpl

package kr.co.kshproject.webDemo.Applicaiton.Comment;

import kr.co.kshproject.webDemo.Domain.Comment.Comment;
import kr.co.kshproject.webDemo.Domain.Comment.CommentRepository;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
@AllArgsConstructor
public class CommentServiceImpl implements CommentService{
    private static final Logger logger = LoggerFactory.getLogger(CommentServiceImpl.class);
    private final CommentRepository commentRepository;

    @Override
    public Comment save(Comment comment) {
        LocalDate now = LocalDate.now();
        comment.setCreatedDate(now.toString());
        comment.setUserName("admin");
        return commentRepository.save(comment);
    }

    @Override
    public List<Comment> findAll() {
        return commentRepository.findAll();
    }

    @Override
    public Optional<Comment> findById(Long id) {
        return commentRepository.findById(id);
    }

    @Override
    public Comment update(Long id, Comment saveComment) {
        Optional<Comment> findComment =commentRepository.findById(id);
        if(findComment.isPresent()==false){
            return null;
        }
        Comment comment=findComment.get();
        comment.setContents(saveComment.getContents());

        return commentRepository.save(comment);
    }

    @Override
    public void deleteAll() {
        commentRepository.deleteAll();
    }
}

컨트롤러:
CommentController

package kr.co.kshproject.webDemo.interfaces.Comment;

import kr.co.kshproject.webDemo.Applicaiton.Comment.CommentService;
import kr.co.kshproject.webDemo.Domain.Comment.Comment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {
    private final CommentService commentService;

    @Autowired
    public CommentController(CommentService commentService){
        this.commentService=commentService;
    }

    @PostMapping
    public ResponseEntity<Comment> save(@RequestBody Comment comment){
        return ResponseEntity.ok(commentService.save(comment));
    }

    @GetMapping
    public ResponseEntity<List<Comment>> findAll(){
        return ResponseEntity.ok( commentService.findAll());
    }

    @GetMapping("/{id}")
    public Optional<Comment> findById(@PathVariable Long id){
        return commentService.findById(id);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Comment> update(@PathVariable Long id, @RequestBody Comment comment){
        return ResponseEntity.ok(commentService.update(id,comment));
    }

    @DeleteMapping
    public void deleteAll(){
        commentService.deleteAll();
    }
}

 테스트 코드:
CommentSerive 테스트 코드

package kr.co.kshproject.webDemo.Applicaiton.Comment;

import kr.co.kshproject.webDemo.Applicaiton.Notice.NoticeServiceImpl;
import kr.co.kshproject.webDemo.Domain.Comment.Comment;
import kr.co.kshproject.webDemo.Domain.Comment.CommentRepository;
import kr.co.kshproject.webDemo.Domain.Notice.Notice;
import kr.co.kshproject.webDemo.Domain.Notice.NoticeRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

class CommentServiceImplTest {
    @Mock
    private NoticeRepository noticeRepository;

    @Mock
    private CommentRepository commentRepository;

    @InjectMocks
    private NoticeServiceImpl noticeService;
    
    @InjectMocks
    private CommentServiceImpl commentService;

    @BeforeEach
    void setUp(){
        MockitoAnnotations.openMocks(this);
    }

    @AfterEach
    void afterEach(){
        noticeService.deleteAll();
        commentService.deleteAll();
    }

    @Test
    void save() throws Exception{
        //생성
        // Notice 생성 및 저장
        Notice notice = new Notice(null, "test", "title", "contents", "email", "date", null);

        // 저장 동작을 모의화
        when(noticeRepository.save(any(Notice.class))).thenReturn(notice);

        // Comment 생성 및 저장
        Comment comment = new Comment(null, null, "test", "comment", "date");
        when(commentRepository.save(any(Comment.class))).thenReturn(comment);
        comment.setNotice(notice);

        Optional<Comment> findComment= Optional.ofNullable(commentService.save(comment));
        assertThat(findComment.get()).isEqualTo(comment);
    }

    @Test
    void findAll() throws Exception{
        //생성
        // Notice 생성 및 저장
        Notice notice= new Notice(null,"test1","title","cotenst","email","date",null);
        // 저장 동작을 모의화
        when(noticeRepository.save(any(Notice.class))).thenReturn(notice);

        // Comment 생성 및 저장
        Comment comment1 = new Comment(null, notice, "test1", "comment1", "date");
        Comment comment2 = new Comment(null, notice, "test2", "comment2", "date");

        when(commentRepository.findAll()).thenReturn(Arrays.asList(comment1, comment2));

        //find
        List<Comment> result = commentService.findAll();
        assertThat(result.size()).isEqualTo(2);
        assertThat(result).contains(comment1, comment2);
    }

    @Test
    void findById() throws Exception {
        Long id = 1L;
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        // 저장 동작을 모의화
        when(noticeRepository.findById(id)).thenReturn(Optional.of(notice));

        Comment comment = new Comment(null, notice, "test", "comment", "date");

        when(commentRepository.findById(id)).thenReturn(Optional.of(comment));

        Optional<Comment> foundComment = commentService.findById(id);
        assertThat(foundComment.get()).isEqualTo(comment);
    }

    @Test
    void update() throws Exception {
        //생성
        // Notice 생성 및 저장
        Long id = 1L;
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        // 저장 동작을 모의화
        when(noticeRepository.findById(id)).thenReturn(Optional.of(notice));

        Comment existingComment = new Comment(id, notice, "test", "comment", "date");
        Comment updatedComment = new Comment(id, notice, "test", "newContent", "date");
        //when
        when(commentRepository.findById(id)).thenReturn(Optional.of(existingComment));
        when(commentRepository.save(any(Comment.class))).thenAnswer(invocation -> invocation.getArgument(0));
        Comment result = commentService.update(id, updatedComment);

        //then
        assertThat(result.getId()).isEqualTo(id);
        assertThat(result.getContents()).isEqualTo("newContent");
    }
}

CommentController 테스트 코드 

package kr.co.kshproject.webDemo.interfaces.Comment;

import kr.co.kshproject.webDemo.Applicaiton.Comment.CommentService;
import kr.co.kshproject.webDemo.Applicaiton.Notice.NoticeService;
import kr.co.kshproject.webDemo.Domain.Comment.Comment;
import kr.co.kshproject.webDemo.Domain.Notice.Notice;
import kr.co.kshproject.webDemo.interfaces.Notice.NoticeController;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.Arrays;
import java.util.Optional;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

class CommentControllerTest {
    private MockMvc mockMvc1;
    private MockMvc mockMvc2;

    @Mock
    private NoticeService noticeService;

    @InjectMocks
    private NoticeController noticeController;

    @Mock
    private CommentService commentService;

    @InjectMocks
    private CommentController commentController;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        mockMvc1 = MockMvcBuilders.standaloneSetup(noticeController).build();
        mockMvc2=MockMvcBuilders.standaloneSetup(commentController).build();
    }

    @Test
    void save() throws Exception {
        //생성
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        //저장
        when(noticeService.save(any(Notice.class))).thenReturn(notice);

        //체크
        mockMvc1.perform(post("/notice")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{}"))
                .andExpect(status().isOk());

        Comment comment = new Comment(null, null, "test", "comment", "date");

        //저장
        when(commentService.save(any(Comment.class))).thenReturn(comment);
        comment.setNotice(notice);
        //체크
        mockMvc2.perform(post("/comment")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{}"))
                .andExpect(status().isOk());

    }

    @Test
    void findAll() throws Exception{
        //생성
        //생성
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        //저장
        when(noticeService.save(any(Notice.class))).thenReturn(notice);

        //체크
        mockMvc1.perform(post("/notice")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{}"))
                .andExpect(status().isOk());

        //생성
        Comment comment1 = new Comment(null, null, "test", "comment1", "date");
        Comment comment2 = new Comment(null, null, "test", "comment2", "date");

        //저장
        when(commentService.findAll()).thenReturn(Arrays.asList(comment1, comment2));
        comment1.setNotice(notice);
        comment2.setNotice(notice);
        //체크
        mockMvc2.perform(get("/comment"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

    @Test
    void findById() throws Exception{
        Long id = 1L;
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        //저장
        when(noticeService.save(any(Notice.class))).thenReturn(notice);

        //체크
        mockMvc1.perform(get("/notice/"+id))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));

        Comment comment = new Comment(null, null, "test", "comment", "date");

        //저장
        when(commentService.save(any(Comment.class))).thenReturn(comment);
        comment.setNotice(notice);
        //체크
        mockMvc2.perform(get("/comment/"+id))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

    @Test
    void update() throws Exception{
        Long id = 1L;

        //생성
        Notice notice= new Notice(null,"test","title","cotenst","email","date",null);

        //저장
        when(noticeService.save(any(Notice.class))).thenReturn(notice);

        //체크
        mockMvc1.perform(post("/notice")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{}"))
                .andExpect(status().isOk());

        Comment existingComment = new Comment(id, notice, "test", "oldComment", "date");
        Comment updatedComment  = new Comment(id, notice, "test", "newComment", "date");

        when(commentService.findById(id)).thenReturn(Optional.of(existingComment));
        when(commentService.update(eq(id), any(Comment.class))).thenReturn(updatedComment);

        mockMvc2.perform(put("/comment/" + id)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"contents\":\"newComment\"}"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.contents").value("newComment"));
    }
}

+ Recent posts