Spring Boot DB 연동과 테스트 Spring Boot DB Connection and Testing
SpringBoot 를 사용해 DB 연결하기 - H2
많이 사용되는 데이터베이스인 MySQL 사용에 앞서, 테스트를 위해 H2 데이터베이스를 사용해서, 간단한 로직을 작성 해 보고, 테스트까지 해 보려고 한다
SpringBoot 패키지 관리하기
나는 Gradle로 관리 패키지를 관리 하려고 한다. 이전에는 Maven에서 관리를 했었지만, 사용하다보니 Gradle이 좀 더 직관적이고 편하다는 느낌을 많이 받았다. (사실, 패키지 이름만 같다면 상관없을 것 같다)
build.gradle 파일에서 아래와 같이 세팅 해 주었다

Dependency 설정이 완료가 되었기 때문에, SpringBoot가 잘 실행이 되도록 설정값들을 아래와 같이 넣어주자
가장 처음 세팅을 할 수 있는 파일은 application.properties 이지만, 나는 application.yml을 새로 만들어 Hierarchy를 표현해서 보기 편하도록 작성했다.

세팅이 완료되었기 때문에 이제 간단한 application을 만들어보자
Model 생성하기
데이터를 넣기 위해서는, 데이터를 저장 할 수 있는 테이블을 H2에 만들고 데이터의 형태를 명시 해 주어야 한다
기본 패키지 안쪽으로 model 패키지를 만들고, 내부에 UserModel을 생성했다.

모델은 가장 기본적인 User를 나타내는 것들을 사용 해 보려고 한다. 이것을 기반으로 나중에 로그인/로그아웃/회원가입 등 여러가지 서비스로 확장 해 볼 수 있을 것 같다.
Repository 만들기
위에서 생성 한 User Model을 가지고 Repository를 만들어주자. 지금은 기본적인 Save Method를 조금만 개선해서 테스트 해 보려고 하기 때문에 큰 작업은 필요 없다

@Repository 어노테이션으로 레포지터리를 나타내어주었고, JpaRepository를 상속받아 기본적인 메서드들을 사용하고, findByName메서드를 만들어서 username으로 찾을 수 있도록 함수를 만들어주었다
Test Class 만들기(Junit4)
위에서 생성한 Repository를 가지고 간단한 테스트를 해 보자. User 모델을 가지고 CRUD 테스트를 해 보려고 한다.
Create 는 데이터를 생성하는 것 이기때문에 Table 생성과 Repository를 잘 작성했는지에 대해서 테스트 해 볼 수 있을 것이다. 때문에 선제조건이 크게 필요하지 않을 것 같다
다만 Read, Update, Delete는 데이터를 찾아서 읽고, 수정하고 삭제하는 과정이기 때문에 Repository의 함수로 가져온 데이터의 유무가 중요하다.
이번에 진행 할 때는 테스트코드에 실행 순서들을 입혀서 데이터를 생성 한 후에 이어지는 동작들을 테스트 해 보려고 한다
여기서는 Junit4를 사용한다. 사용하려고 하는 기능들이 Junit5에서는 좀 더 편하게 수정되었다. 이부분들은 다시한번 다뤄보려고한다.
우선, 테스트 해 볼 클래스를 하나 생성하고 테스트 할 전체적인 클래스의 구성을 만든다

@Autowired 어노테이션으로 Repository를 연결 해 준다
Test Class에 새로운 @FixMethodOrder 어노테이션을 적용해서 테스트 함수별로 순서를 적용 할 수 있도록 작업 해 주려고 한다. 지금은 NAME_ASCENDING 옵션을 주었지만, 다른 옵션들도 있다.

NAME_ASCENDING 옵션에서 알 수 있듯이, 테스트 함수이름에 따라서 정렬 해 준다. 함수 이름에 번호를 매기고, 어떤 기능을 할 수 있을지 대략적으로 나타내었다

Test 함수 - Create

우선 뒤에서 Read, Update, Delete에서 사용할 데이터이니까 잘 확인 해 보도록 하자
Test 함수 - Read

Test 함수 - Update

Test 함수 - Delete
Connecting to a Database with SpringBoot - H2
Before using MySQL, a commonly used database, I’ll use the H2 database for testing purposes, write some simple logic, and run tests.
Managing SpringBoot Packages
I plan to manage packages with Gradle. Previously, I used Maven for management, but after using both, I felt that Gradle is more intuitive and convenient. (Actually, as long as the package names are the same, it probably doesn’t matter.)
I configured the build.gradle file as follows:

Since the dependency configuration is complete, let’s add the configuration values so that SpringBoot runs properly.
The first file you can configure is application.properties, but I created a new application.yml to express hierarchy and make it easier to read.

Now that the setup is complete, let’s create a simple application.
Creating the Model
To insert data, we need to create a table in H2 where data can be stored and specify the data format.
I created a model package inside the base package and created a UserModel inside it.

The model will represent the most basic User elements. Based on this, I think we can later expand to various services like login/logout/registration.
Creating the Repository
Let’s create a Repository with the User Model we created above. Since I’m just trying to test with a slightly improved basic Save Method, no major work is needed.

I indicated the repository with the @Repository annotation, inherited from JpaRepository to use basic methods, and created a findByName method to search by username.
Creating the Test Class (Junit4)
Let’s do a simple test with the Repository created above. I’m going to test CRUD with the User model.
Create is about generating data, so we can test whether the table creation and Repository were written correctly. Therefore, there shouldn’t be much need for preconditions.
However, Read, Update, and Delete are processes of finding, reading, modifying, and deleting data, so the presence of data retrieved by the Repository function is important.
This time, I’ll apply execution order to the test code to test the subsequent operations after creating the data.
I’m using Junit4 here. The features I want to use have been made more convenient in Junit5. I plan to cover that again later.
First, create a class to test and set up the overall class structure for testing.

Connect the Repository with the @Autowired annotation.
I’m going to apply a new @FixMethodOrder annotation to the Test Class to enable ordering for each test function. I’ve given it the NAME_ASCENDING option for now, but there are other options as well.

As you can tell from the NAME_ASCENDING option, it sorts according to test function names. I numbered the function names and roughly indicated what each function does.

Test Function - Create

First, let’s verify this carefully since this data will be used in Read, Update, and Delete later.
Test Function - Read

Test Function - Update

Test Function - Delete
댓글남기기