ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] REST API 만들기(8) - Service 구현 및 테스트(Junit4)
    Spring Boot/2.4.x - REST API 만들기 2020. 5. 9. 16:59
    반응형

    업무 로직을 구현하기 위해서는 서비스 클래스가 필요하므로, BoardService 인터페이스, BoardServiceImpl 클래스를 구현한 후 테스트를 진행하겠습니다.

     

    1. Servie 구현 

    서비스 인터페이스와 서비스 구현 클래스는 한 쌍으로 만들기도 하고, 서비스 클래스만 만들기도 하는데 인터페이스와 구현 클래스를 구분하기 위해 BoardService 클래스를 인터페이스로 수정하고, com.api.board.service.Impl 패키지를 생성한 후 BoardServiceImpl 클래스를 추가하세요.

    BookService.java

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    package com.api.board.service;
     
    import java.util.List;
     
    import com.api.board.domain.Board;
     
    public interface BoardService {
        
        /** 게시글 목록 조회 */
        public List<Board> getBoardList() throws Exception; 
        
        /** 게시글 상세 조회 */
        public Board getBoardDetail(int board_seq) throws Exception;
     
        /** 게시글 등록 */
        public int insertBoard(Board board) throws Exception;
     
        /** 게시글 수정 */
        public int updateBoard(Board board) throws Exception;
     
        /** 게시글 삭제 */
        public int deleteBoard(int board_seq) throws Exception;
    }
    cs

     

    서비스 클래스임을 스프링에 알려주기 위해서 @Service 어노테이션을 클래스에 추가하세요. 어노테이션 기반의 트랜잭션 관리를 위해서 클래스에 @Transactional 어노테이션도 추가하세요. 서비스 클래스에 읽기 전용은 @Transactional(readOnly = true) 어노테이션을 추가하고, 등록/수정/삭제 메소드에는 트랜잭션을 사용하도록 @Transactional(readOnly = false, propagation = Propagation.REQUIRED) 을 추가하세요.

    BoardServiceImpl.java

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    package com.api.board.service.Impl;
     
    import java.util.List;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
     
    import com.api.board.domain.Board;
    import com.api.board.mapper.BoardMapper;
    import com.api.board.service.BoardService;
     
    @Transactional(readOnly = true)
    @Service
    public class BoardServiceImpl implements BoardService {
     
        @Autowired
        private BoardMapper boardMapper;
     
        /** 게시글 목록 조회 */
        public List<Board> getBoardList() throws Exception {
            return boardMapper.getBoardList();
        }
     
        /** 게시글 상세 조회 */
        public Board getBoardDetail(int board_seq) throws Exception {
            return boardMapper.getBoardDetail(board_seq);
        };
     
        /** 게시글 등록 */
        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
        public int insertBoard(Board board) throws Exception {
            return boardMapper.insertBoard(board);
        };
     
        /** 게시글 수정 */
        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
        public int updateBoard(Board board) throws Exception {
            return boardMapper.updateBoard(board);
        };
     
        /** 게시글 삭제 */
        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
        public int deleteBoard(int board_seq) throws Exception {
            return boardMapper.deleteBoard(board_seq);
        };
    }
    cs

     

    2. Service 테스트

    @Transactional 어노테이션을 선언하면 테스트 메소드가 끝날 때마다 transaction을 롤백합니다. 테스트 메소드에 @Rollback 어노테이션을 추가해서 메소드 별로 Rollback 여부를 설정할 수 있습니다.

    BookServiceTest.java  

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    package com.api.board.service;
     
    import static org.junit.Assert.assertNotNull;
    import static org.junit.Assert.assertTrue;
     
    import java.util.List;
     
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.annotation.Rollback;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.Transactional;
     
    import com.api.board.domain.Board;
     
    @Transactional
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BoardServiceTest {
     
        Logger logger = LoggerFactory.getLogger(BoardServiceTest.class);
     
        @Autowired
        BoardService boardService;
     
        /** 게시글 목록 조회 시 NULL 아니면 테스트 통과 */
        @Test
        public void testGetBoardList() {
             try {
                 
                 List<Board> boardList = boardService.getBoardList();
                 assertNotNull(boardList.size());
                 
             } catch (Exception e) {
                 e.printStackTrace();
             }
        }
     
        /** 게시글 상세 조회 시 NULL이 아니면 테스트 통과 */
        @Test
        public void testGetBoardDetail() {
            
            try {
                
                List<Board> bookList = boardService.getBoardList();
                int boardSeq = bookList.get(0).getBoard_seq();
                
                Board bookDetail = boardService.getBoardDetail(boardSeq);
                assertNotNull(bookDetail);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        @Rollback(true)
        @Test
        public void testInsertBoard() {
            
            try {
     
                Board board = new Board();
                board.setBoard_writer("게시글 작성자 등록");
                board.setBoard_subject("게시글 제목 등록");
                board.setBoard_content("게시글 내용 등록");            
                
                int result = boardService.insertBoard(board);            
                assertTrue(result == 1);
     
            } catch (Exception e) {
                e.printStackTrace();
            }        
        }
     
        /** 게시글 수정 후 1이 응답되면 테스트 통과 */
        @Rollback(true)
        @Test
        public void testUpdateBoard() {
            
            try {
                
                List<Board> bookList = boardService.getBoardList();
                int boardSeq = bookList.get(0).getBoard_seq();
     
                Board board = new Board();
                board.setBoard_seq(boardSeq);
                board.setBoard_subject("게시글 제목 수정");
                board.setBoard_content("게시글 내용 수정");
                
                int result = boardService.updateBoard(board);
                assertTrue(result == 1);
     
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /** 게시글 삭제 후 1이 응답되면 테스트 통과 */
        @Rollback(true)
        @Test
        public void testDeleteBoard() {
     
            try {
                
                List<Board> bookList = boardService.getBoardList();
                int boardSeq = bookList.get(0).getBoard_seq();
                
                int result = boardService.deleteBoard(boardSeq);            
                assertTrue(result == 1);
     
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    cs

     

    소스 코드는 Github Repository - https://github.com/tychejin1218/api-board_v1 (branch : section08) 를 참조하세요.
    Github에서 프로젝트 가져오기 - 
    https://tychejin.tistory.com/33

    반응형

    댓글

Designed by Tistory.