ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 4. SpringBoot + JPA + H2 database
    Project/React+Java 2022. 7. 21. 18:54

    https://github.com/dchkang83/project-board

     

    GitHub - dchkang83/project-board

    Contribute to dchkang83/project-board development by creating an account on GitHub.

    github.com

     

    1. H2 - 의존성 추가

    testImplementation group: 'com.h2database', name: 'h2', version: '2.1.214'

     

    2. H2 - apllication.yml

    spring:
      datasource:
        driver-class-name: org.h2.Driver
        url: jdbc:h2:mem:test
        username: sa
        password:

     

    3. JPA - 의존성 추가

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

     

    4. JPA - application.yml

    spring:
      ...
      jpa:
        hibernate:
          ddl-auto: create #create update none
          naming:
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        show-sql: true

     

    5. User Repository interface

    package com.main.gundam.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import com.main.gundam.domain.User;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        public User findByUsername(String username);
    }


    6. User Entity class

    package com.main.gundam.domain;
    
    import lombok.Data;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    @Data
    @Table(name = "TEST") // user table은 이미 사용하고 있는경우가 ..많아서 선언해줌
    @Entity
    public class User {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        // @GeneratedValue(strategy = GenerationType.AUTO)
        private long userNo;
        private String username;
        private String password;
        private String roles; // USER, ADMIN
        
        public List<String> getRoleList() {
            if (this.roles.length() > 0) {
                return Arrays.asList(this.roles.split(","));
            }
    
            return new ArrayList<>();
        }
    }

     

    7. Repository Test Case

    package com.main.gundam.repository;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.annotation.Rollback;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.Assertions;
    import com.main.gundam.domain.User;
    import lombok.extern.slf4j.Slf4j;
    
    // @RunWith(SpringRunner.class)
    @SpringBootTest // 전체 빈을 다 등록하고, 모든 application.yml를 반영해서 테스트를 하기 때문에 통합테스트용으로 많이 사용
    @Rollback(true)
    @Slf4j
    public class UserRepositoryTests {
        
        @Autowired
        private UserRepository userRepository;
    
        @Test
        public void saveUserTest() {
            //given
            User user = new User();
            user.setUsername("test_user111");
    
            // when
            userRepository.save(user);
    
            User retrivedUser = userRepository.findById(user.getUserNo()).get();
    
            // then
            Assertions.assertEquals(retrivedUser.getUsername(), "test_user111");
        }
    }

     

    8. User Service class

    package com.main.gundam.service;
    
    
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.main.gundam.domain.User;
    import com.main.gundam.repository.UserRepository;
    
    import lombok.RequiredArgsConstructor;
    
    @Service
    @RequiredArgsConstructor
    @Transactional
    public class UserService {
        private final UserRepository userRepository;
    
        public Long addUser(User user) {
            return userRepository.save(user).getUserNo();
        }
    }

     

    9. Service Test Case

    package com.main.gundam.service;
    
    import static org.mockito.ArgumentMatchers.anyString;
    import static org.mockito.BDDMockito.any;
    import static org.mockito.BDDMockito.given;
    
    import java.util.Optional;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.annotation.Rollback;
    import org.springframework.test.util.ReflectionTestUtils;
    import org.springframework.util.Assert;
    
    import com.main.gundam.domain.User;
    import com.main.gundam.repository.UserRepository;
    
    import lombok.extern.slf4j.Slf4j;
    
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.jupiter.MockitoExtension;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.DisplayName;
    
    // @RunWith(SpringRunner.class)
    @ExtendWith(MockitoExtension.class)
    @Slf4j
    public class UserServiceTests {
    
        @InjectMocks
        private UserService userService;
    
        @Mock
        private UserRepository userRepository;
        
        @Test
        @DisplayName("사용자 등록")
        public void saveUserTest() {
            //given
            User user = new User();
            user.setUsername("test_user111");
            
            Long fakeUserNo = (long) 111;
            ReflectionTestUtils.setField(user, "userNo", fakeUserNo);
    
            // mocking
            given(userRepository.save(any()))
                .willReturn(user);
            given(userRepository.findById(fakeUserNo))
                .willReturn(Optional.ofNullable(user));
    
            // when
            Long newUserNo = userService.addUser(user);
            User retrivedUser = userRepository.findById(newUserNo).get();
    
            // then
            Assertions.assertEquals(retrivedUser.getUsername(), "test_user111");
        }
    }

    댓글

Designed by Tistory.