본문 바로가기

토이프로젝트/리뷰어(영화 리뷰 사이트)

13일차 - 테스트 DB 구성 및 domain단 구현

오늘은 어제 설계한 도메인이 제대로 테이블을 생성하는지 확인할 겸 테스트 DB를 연결했다.

spring boot와 h2 연결

test용으로 계속 사용할 것이기 때문에 h2 database의 in memory 방식을 사용했다.

의존성으로 지정한 모든 목록은 다음과 같다.

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    implementation  'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'com.mysql:mysql-connector-j'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'

그리고 yml 파일에서 db 정보를 설정하고 실행하면 잘 될 것이다.

server:
  port: 8080
spring:
  h2:
    console:
      enabled: true
      path: /h2-console
      settings:
        web-allow-others: true
  datasource:
    driver-class-name: org.h2.Driver
    url: "jdbc:h2:mem:reviewer_test_db;MODE=MYSQL;DB_CLOSE_DELAY=-1"
    username: sa
    password:
    hikari:
      minimum-idle: 1
      maximum-pool-size: 5
      pool-name: H2_DB
  jpa:
    show-sql: true
    defer-datasource-initialization: true
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create-drop

 

 

프로젝트 실행 후 http://localhost:8080/h2-console로 접속하면

db 연결 페이지가 나와야 하는데

실행이 제대로 되지 않고 처음 보는 창이 떴다.

 

Please sign in

이 창이 뜨는 이유는 의존성 목록에 이유가 있었다.

implementation 'org.springframework.boot:spring-boot-starter-security'

해당 의존성을 주입할 경우 security가 적용되기 때문에 security에서 h2-console 주소에 대한 설정을 먼저 해야했다.

 

 

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }

  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers(
        "/h2-console/**");
  }
}

 

이렇게 WebSecurityConfigurerAdapter를 상속하는 클래스를 구현해주면 h2-console 주소에 접근할 수 있다.

 

 

 

더미데이터 생성

더미데이터를 미리 생성해서 db에 넣어주기로 했다.

 

열심히 데이터를 넣고나서 생각해보니, 이 데이터는 test할 때 사용되는 건데

단위테스트 한번마다 테이블을 초기화 시켜줘야할 텐데 이 데이터를 계속 활용할 수 있을지 의문이다.

괜한 짓을 한 거일 수도 있겠다...ㅠㅠ