Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Stack
- 달빛클럽1기
- dfs
- 경제공부
- React.js
- 리액트
- Java
- 완전탐색
- 달빛캠퍼스
- 노마드코더 강의
- React
- 노마드코더
- 인플레이션에서 살아남기
- 백준
- 프로그래머스
- JPA
- 알고리즘
- 카카오블라인드코딩테스트
- Algorithm
- HashMap
- 달빛클럽
- 자바
- 재귀
- 달빛클럽 1기
- Array
- BOJ
- SoftwareExpertAcademy
- programmers
- ReactJS로 영화 웹 서비스 만들기
- SWEA
Archives
- Today
- Total
th42500의 TIL
[Spring, JUnit] JUnit5를 적용한 UserDao Test 코드 작성 본문
Backend/Spring & SpringBoot
[Spring, JUnit] JUnit5를 적용한 UserDao Test 코드 작성
th42500 2022. 10. 18. 22:11오늘은 그동안 작성했던 UserDao에 작성한 메서드들을 테스트 코드를 통해 잘 작동하는지 테스트해보려 한다.
❓ 테스트 코드를 작성해야 하는 이유
✔ 개발 과정에서 문제를 조기에 발견할 수 있음
✔ 리팩토링의 리스크가 감소함
✔ 애플리케이션을 가동해서 직접 테스트하는 것보다 테스트를 빠르게 진행할 수 있음
✔ 명세 문서로서의 기능을 수행할 수 있음
✔ 코드가 작성된 목적을 명확하게 표현할 수 있으며, 불필요한 내용이 추가되는 것을 방지할 수 있음
❓ JUnit이란?
✔ 자바 언어에서 사용되는 대표적인 테스트 플레임워크로서, 단위 테스트를 위한 도구를 제공
📌 JUnit5를 적용한 UserDao Test 코드 작성
[ UserDao.java ]
package com.sping.dao;
import com.sping.domain.User;
import java.sql.*;
import java.util.List;
public class UserDao {
private AWSConnectionMaker awsConnectionMaker;
private ConnectionMaker connectionMaker;
public UserDao() {
this.connectionMaker = new AWSConnectionMaker();
}
public List<User> selectAll() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<User> userList = null;
try {
conn = connectionMaker.getConnection();
pstmt = conn.prepareStatement("select * from users");
rs = pstmt.executeQuery();
while(rs.next()) {
User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password"));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionClose.close(conn, pstmt, rs);
}
return userList;
}
public User selectById(String sId) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
User user = null;
try{
conn = connectionMaker.getConnection();
pstmt = conn.prepareStatement("select id, name, password from users where id = ?");
pstmt.setString(1, sId);
rs = pstmt.executeQuery();
if(rs.next()) {
user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionClose.close(conn, pstmt, rs);
}
return user;
}
public void add(User user) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = connectionMaker.getConnection();
pstmt = conn.prepareStatement("insert into users(id, name, password) values (?, ?, ?)");
pstmt.setString(1, user.getId());
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getPassword());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionClose.close(conn, pstmt);
}
}
public void deleteAll() {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = connectionMaker.getConnection();
pstmt = conn.prepareStatement("delete from users");
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionClose.close(conn, pstmt);
}
}
public int getCount() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int cnt = 0;
try{
conn = connectionMaker.getConnection();
pstmt = conn.prepareStatement("select count(*) from users");
rs = pstmt.executeQuery();
if (rs.next()) {
cnt = rs.getInt(1);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
ConnectionClose.close(conn, pstmt);
}
return cnt;
}
}
[UserDaoTest.java]
package com.sping.dao;
import com.sping.domain.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UserDaoTest {
UserDao userDao;
@BeforeEach
void setUp() {
userDao = new UserDao();
userDao.deleteAll();
}
@Test
@DisplayName("add기능 & select 테스트")
void addAndSelectById() {
User user = new User("0", "Soyeong", "1234");
userDao.add(user);
assertEquals("Soyeong", userDao.selectById("0").getName());
}
@Test
@DisplayName("데이터 개수 세기 테스트")
void getCount() {
assertEquals(0, userDao.getCount());
User user = new User("0", "Soyeong", "1234");
userDao.add(user);
assertEquals(1, userDao.getCount());
}
@Test
@DisplayName("deletAll 테스트")
void deleteAll() {
userDao.deleteAll();
assertEquals(0, userDao.getCount());
}
}
UserDaoTest에 사용된 Annotation
- @Test : 테스트 코드를 포함한 메서드를 정의
- @BeforAll : 테스트를 시작하기 전에 호출되는 메서드를 정의
- @BeforeEach : 각 테스트 메서드가 실행되기 전에 동작하는 메서드를 정의
- @AfterAll : 테스트를 종료하면서 호출되는 메서드를 정의
- @AfterEach : 각 테스트 메서드가 종료되면서 호출되는 메서드를 정의
[ 테스트 결과 ]
테스트 결과 모든 테스트가 잘 통과하는 것을 확인할 수 있었다.
'Backend > Spring & SpringBoot' 카테고리의 다른 글
[Spring] uses unchecked or unsafe operations. 경고 (0) | 2022.12.07 |
---|---|
[Spring] UserDao Factory 생성 (0) | 2022.10.19 |
[Spring] JDBC API를 이용한 MySQL 연동 (Feat. DriverManager) (0) | 2022.10.18 |
Comments