Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spring-toby-3 [Spring] 2 초난감 DAO (2.3) #5

Merged
merged 4 commits into from
Nov 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,14 @@ project(":chapter1") {
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
}
project(":chapter2") {
dependencies {
// Driver.class 호출하기 위한 implementation 설정
implementation 'mysql:mysql-connector-java'

implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
}
13 changes: 12 additions & 1 deletion chapter1/src/main/java/com/example/chapter1/part2/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,18 @@ public User get(String id) throws SQLException {
}
}

public void del() throws SQLException {
public int getCount() throws SQLException {
try (
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM USERS");
) {
ResultSet rs = ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}

public void truncateTable() throws SQLException {
try (
Connection c = dataSource.getConnection();
Statement s = c.createStatement()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,22 @@ class UserDaoTest {
@DisplayName("DataSource 인터페이스를 사용한 테스트")
@Test
void testCase1() throws SQLException {

UserDao userDao = new UserDao(dataSource);

userDao.truncateTable();
assertThat(userDao.getCount()).isZero();

User actual = new User();
actual.setId("user_id");
actual.setName("user_name");
actual.setPassword("user_password");

userDao.add(actual);

User expected = userDao.get("user_id");
assertThat(userDao.getCount()).isOne();

userDao.del();
User expected = userDao.get("user_id");

assertThat(actual).isEqualTo(expected);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.chapter2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Chapter2Application {
public static void main(String[] args) {
SpringApplication.run(Chapter2Application.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.chapter2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

@Bean
public DataSource dataSource() {
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();

dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class);
dataSource.setUrl("jdbc:mysql://localhost:3309/user-db");
dataSource.setUsername("root");
dataSource.setPassword("1234");

return dataSource;
}
}
73 changes: 73 additions & 0 deletions chapter2/src/main/java/com/example/chapter2/dao/UserDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.example.chapter2.dao;

import com.example.chapter2.domain.User;
import org.springframework.dao.EmptyResultDataAccessException;

import javax.sql.DataSource;
import java.sql.*;

public class UserDao {

private final DataSource dataSource;

public UserDao(DataSource dataSource) {
this.dataSource = dataSource;
}

public void add(User user) throws SQLException {
try (
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("INSERT INTO USERS(id, name, password) values (?, ?, ?)")
) {
ps.setString(1, user.getId());
ps.setString(2, user.getName());
ps.setString(3, user.getPassword());

ps.executeUpdate();
}
}

public User get(String id) throws SQLException {
try (
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT * FROM USERS WHERE id = ?")
) {
ps.setString(1, id);
ResultSet rs = ps.executeQuery();

User user = null;

if(rs.next()) {
user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
}

if(user == null) {
throw new EmptyResultDataAccessException(1);
}
return user;
}
}

public int getCount() throws SQLException {
try (
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM USERS");
) {
ResultSet rs = ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}

public void truncateTable() throws SQLException {
try (
Connection c = dataSource.getConnection();
Statement s = c.createStatement()
) {
s.executeUpdate("TRUNCATE TABLE USERS");
}
}
}
24 changes: 24 additions & 0 deletions chapter2/src/main/java/com/example/chapter2/domain/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.chapter2.domain;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.relational.core.mapping.Table;

@Table(value = "USERS")
@Setter
@Getter
@EqualsAndHashCode(of = "id")
@NoArgsConstructor
public class User {
private String id;
private String name;
private String password;

public User(String id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
}
17 changes: 17 additions & 0 deletions chapter2/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
server:
port: 8000

spring:
profiles:
active: local

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3309/user-db
username: root
password: 1234

sql:
init:
mode: always
schema-locations: schema.sql
17 changes: 17 additions & 0 deletions chapter2/src/main/resources/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
version: '3'

services:
n-db:
image: mysql:latest
container_name: n-db
restart: always
ports:
- "3309:3306"
environment:
- MYSQL_DATABASE=user-db
- MYSQL_ROOT_PASSWORD=1234
- TZ=Asia/Seoul
command:
- --default-authentication-plugin=mysql_native_password
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
7 changes: 7 additions & 0 deletions chapter2/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS USERS
(
id varchar(10),
name varchar(20) not null,
password varchar(20) not null,
primary key (id)
);
88 changes: 88 additions & 0 deletions chapter2/src/test/java/com/example/chapter2/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package com.example.chapter2.dao;

import com.example.chapter2.config.DataSourceConfig;
import com.example.chapter2.domain.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import javax.sql.DataSource;
import java.sql.SQLException;

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


@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
class UserDaoTest {

@Autowired
private DataSource dataSource;
private UserDao userDao;
private User user1;
private User user2;
private User user3;

@BeforeEach
void setUp() throws SQLException {
userDao = new UserDao(dataSource);
userDao.truncateTable();

user1 = new User("user_0", "user_name_0", "1234");
user2 = new User("user_1", "user_name_1", "1234");
user3 = new User("user_2", "user_name_2", "1234");
}

@DisplayName("테이블 데이터 등록 및 조회 테스트")
@Test
void testCase1() throws SQLException {

assertThat(userDao.getCount()).isZero();

userDao.add(user1);
userDao.add(user2);
assertThat(userDao.getCount()).isEqualTo(2);

User expected1 = userDao.get(user1.getId());
assertThat(user1.getName()).isEqualTo(expected1.getName());

User expected2 = userDao.get(user2.getId());
assertThat(user2.getName()).isEqualTo(expected2.getName());
}

@DisplayName("테이블 등록 카운트 테스트")
@Test
void testCase2() throws SQLException {
assertThat(userDao.getCount()).isZero();

userDao.add(user1);
assertThat(userDao.getCount()).isOne();

userDao.add(user2);
assertThat(userDao.getCount()).isEqualTo(2);

userDao.add(user3);
assertThat(userDao.getCount()).isEqualTo(3);

User actual = userDao.get("user_1");

assertThat(actual.getName()).isEqualTo("user_name_1");
}

@DisplayName("데이터 액세스 예외 테스트")
@Test
void testCase3() throws SQLException {
assertThat(userDao.getCount()).isZero();

userDao.add(user1);

assertThatExceptionOfType(EmptyResultDataAccessException.class)
.isThrownBy(() -> userDao.get("111"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.chapter2.test;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import java.util.HashSet;
import java.util.Set;

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

@ContextConfiguration
class JUnitApplicationContextTest {
// 테스트 컨텍스트가 매번 주입해주는 애플리케이션 컨텍스트는 항상 같은 오브젝트인지 테스트로 확인
@Autowired
private ApplicationContext context;
static Set<JUnitApplicationContextTest> testObjects = new HashSet<>();
static ApplicationContext contextObject = null;

@DisplayName("애플리케이션 컨텍스트가 context 변수에 주입되었는지 확인하는 테스트")
@Test
void testCase1() {
assertThat(testObjects).doesNotHaveSameClassAs(this);
testObjects.add(this);

assertThat(contextObject == null || contextObject == this.context).isTrue();
contextObject = this.context;
}

@DisplayName("애플리케이션 컨텍스트가 context 변수에 주입되었는지 확인하는 테스트")
@Test
void testCase2() {
assertThat(testObjects).doesNotHaveSameClassAs(this);
testObjects.add(this);

assertThat(contextObject == null || contextObject == this.context).isTrue();
contextObject = this.context;
}

@DisplayName("애플리케이션 컨텍스트가 context 변수에 주입되었는지 확인하는 테스트")
@Test
void testCase3() {
assertThat(testObjects).doesNotHaveSameClassAs(this);
testObjects.add(this);

// assertThat(contextObject, either(is(nullValue())).or(is(this.context)));
// contextObject = this.context;
}
}
Loading