Web/📗 Spring

Spring '등록' 기능 구현 및 테스트 코드 작성 [Spring / 스프링 부트와 AWS로 혼자 구현하는 웹 서비스]

키깡 2022. 7. 18.
728x90

등록 기능 만들기

  • web > dto > PostsSaveRequestDto
package com.izero.springboot.web.dto;

import com.izero.springboot.domain.posts.Posts;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class PostsSaveRequestDto {
    private Long id;
    private String title;
    private String content;
    private String author;

    @Builder
    public PostsSaveRequestDto(String title, String content, String author){
        this.title = title;
        this.content = content;
        this.author = author;
    }

    public Posts toEntity(){
        return Posts.builder()
                .title(title)
                .content(content)
                .author(author)
                .build();
    }
}
  • service > PostsService
package com.izero.springboot.service.posts;

import com.izero.springboot.domain.posts.PostsRepository;
import com.izero.springboot.web.dto.PostsSaveRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class PostsService {
    private final PostsRepository postsRepository;

    @Transactional
    public Long save(PostsSaveRequestDto requestDto){
        return postsRepository.save(requestDto.toEntity()).getId();
    }
}
  • web > PostsApiController
package com.izero.springboot.web;

import com.izero.springboot.service.posts.PostsService;
import com.izero.springboot.web.dto.PostsSaveRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
public class PostsApiController {
    private final PostsService postsService;

    @PostMapping("/api/v1/posts")
    public Long save(@RequestBody PostsSaveRequestDto requestDto){
        return postsService.save(requestDto);
    }
}

스프링 빈 주입받는 방법

  1. @Autowired
  2. setter
  3. 생성자

이 중 가장 권장되는 것이 생성자로 받는 방법
(@RequiredArgsConstructor 에서 final이 선언 된 모든 필드`를 인자값으로 하는 생성자 생성)

등록 테스트

  • test 폴더 쪽에 PostsApiControllerTest 클래스 만들어 주기
package com.izero.springboot;

import com.izero.springboot.domain.posts.Posts;
import com.izero.springboot.domain.posts.PostsRepository;
import com.izero.springboot.web.dto.PostsSaveRequestDto;
import lombok.Builder;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsApiControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private PostsRepository postsRepository;

    @After
    public void tearDown() throws Exception {
        postsRepository.deleteAll();
    }

    @Test
    public void Posts_등록된다() throws Exception {
        //  given
        String title = "title";
        String content = "content";
        PostsSaveRequestDto requestDto =
                PostsSaveRequestDto.builder().title(title).content(content).author("author").build();   // 빌더 생성

        String url = "http://localhost:" + port + "/api/v1/posts";

        //  when
        ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDto, Long.class);

        //  then
        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(responseEntity.getBody()).isGreaterThan(0L);

        List<Posts> all = postsRepository.findAll();

    }
}

=> 결과 : 결과물로 랜덤 포트 실행과 insert 모두 성공 확인

Image

Image

댓글