테스트에 사용할 User 클래스 만들기

 

User.java

package com.jcy.usedhunter.domain;

import java.util.Date;
import java.util.Objects;

public class User {
    private String id;
    private String pwd;
    private String name;
    private String email;
    private Date birth;
    private String sns;
    private Date reg_date;

    public User(){}
    public User(String id, String pwd, String name, String email, Date birth, String sns, Date reg_date) {
        this.id = id;
        this.pwd = pwd;
        this.name = name;
        this.email = email;
        this.birth = birth;
        this.sns = sns;
        this.reg_date = reg_date;
    }

   
    @Override
	public int hashCode() {
		return Objects.hash(birth, email, id, name, pwd, sns);
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		return Objects.equals(birth, other.birth) && Objects.equals(email, other.email) && Objects.equals(id, other.id)
				&& Objects.equals(name, other.name) && Objects.equals(pwd, other.pwd) && Objects.equals(sns, other.sns);
	}
	@Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", pwd='" + pwd + '\'' +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", birth=" + birth +
                ", sns='" + sns + '\'' +
                ", reg_date=" + reg_date +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public String getSns() {
        return sns;
    }

    public void setSns(String sns) {
        this.sns = sns;
    }

    public Date getReg_date() {
        return reg_date;
    }

    public void setReg_date(Date reg_date) {
        this.reg_date = reg_date;
    }
}

 

 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3301/usedhunter?useUnicode=true&amp;characterEncoding=utf8"></property>
		<property name="username" value="jcy"></property>
		<property name="password" value="zz!"></property>
	</bean>
	</beans>

 

 

 

DBConnectionTest2Test.java

 

 

package com.jcy.usedhunter;

import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jcy.usedhunter.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class DBConnectionTest2Test{
	
	@Autowired
	DataSource ds;
	
	// 사용자 정보를 user_info 테이블에 저장하는 메서드
	public int insertUser(User user) throws Exception{
		Connection conn = ds.getConnection();
		
//		INSERT INTO `usedhunter`.`user_info`(`id`,`pwd`,`name`,`email`,`birth`,`sns`,`reg_date`)
//		VALUES('asdf2','1234','smith','aaa@aaa.com','2021-01-01','facebook',now());

		String sql = "INSERT INTO `usedhunter`.`user_info` VALUES(?, ?, ?, ?, ?, ?, now())";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getPwd());
		pstmt.setString(3, user.getName());
		pstmt.setString(4, user.getEmail());
		pstmt.setDate(5, new java.sql.Date(user.getBirth().getTime())); // util.Date 인 user.getBirth() 를 sql.Date 로 변환
		pstmt.setString(6, user.getSns());
		
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
	
	@Test
	public void insertUserTest() throws Exception{
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		int rowCnt = insertUser(user);
		
		assertTrue(rowCnt==1);
		
	}
	@Test
	public void main() throws Exception{
//		ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
//	      DataSource ds = ac.getBean(DataSource.class);

	      Connection conn = ds.getConnection(); // 데이터베이스의 연결을 얻는다.

	      System.out.println("conn = " + conn);
	      assertTrue(conn!=null); // 괄호 안의 조건식이 true면 테스트 성공, 아니면 실패
	}
}

 

 

 

DBConnectionTest2Test.java 실행

 

DB에 잘 저장이 되었다

package com.jcy.usedhunter;

import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jcy.usedhunter.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class DBConnectionTest2Test{
	
	@Autowired
	DataSource ds;
	
	// 사용자 정보를 user_info 테이블에 저장하는 메서드
	public int insertUser(User user) throws Exception{
		Connection conn = ds.getConnection();
		
//		INSERT INTO `usedhunter`.`user_info`(`id`,`pwd`,`name`,`email`,`birth`,`sns`,`reg_date`)
//		VALUES('asdf2','1234','smith','aaa@aaa.com','2021-01-01','facebook',now());

		String sql = "INSERT INTO `usedhunter`.`user_info` VALUES(?, ?, ?, ?, ?, ?, now())";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getPwd());
		pstmt.setString(3, user.getName());
		pstmt.setString(4, user.getEmail());
		pstmt.setDate(5, new java.sql.Date(user.getBirth().getTime())); // util.Date 인 user.getBirth() 를 sql.Date 로 변환
		pstmt.setString(6, user.getSns());
		
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
	
	@Test
	public void insertUserTest() throws Exception{
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		int rowCnt = insertUser(user);
		
		assertTrue(rowCnt==1);
		
	}
	@Test
	public void main() throws Exception{
//		ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
//	      DataSource ds = ac.getBean(DataSource.class);

	      Connection conn = ds.getConnection(); // 데이터베이스의 연결을 얻는다.

	      System.out.println("conn = " + conn);
	      assertTrue(conn!=null); // 괄호 안의 조건식이 true면 테스트 성공, 아니면 실패
	}
}

 

deleteAll() 메서드 만들기

private void deleteAll() throws Exception{
		Connection conn = ds.getConnection();


		String sql = "delete from `usedhunter`.`user_info`";

		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상

		pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
	}

 

 

 

selectUser() 메서드 만들기

package com.jcy.usedhunter;

import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jcy.usedhunter.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class DBConnectionTest2Test{
	
	@Autowired
	DataSource ds;
	
	
	@Test
	public void insertUserTest() throws Exception{
		deleteAll();
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		int rowCnt = insertUser(user);
		
		assertTrue(rowCnt==1);
		
	}
	
	@Test
	public void selectUserTest() throws Exception {
		deleteAll();
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		insertUser(user);
		User user2 = selectUser("asdf");
		
		assertTrue(user2.getId().equals("asdf"));
	}
	
	
	// 사용자 정보를 user_info 테이블에 저장하는 메서드
	public int insertUser(User user) throws Exception{
		Connection conn = ds.getConnection();
		
//		INSERT INTO `usedhunter`.`user_info`(`id`,`pwd`,`name`,`email`,`birth`,`sns`,`reg_date`)
//		VALUES('asdf2','1234','smith','aaa@aaa.com','2021-01-01','facebook',now());
		
		String sql = "INSERT INTO `usedhunter`.`user_info` VALUES(?, ?, ?, ?, ?, ?, now())";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getPwd());
		pstmt.setString(3, user.getName());
		pstmt.setString(4, user.getEmail());
		pstmt.setDate(5, new java.sql.Date(user.getBirth().getTime())); // util.Date 인 user.getBirth() 를 sql.Date 로 변환
		pstmt.setString(6, user.getSns());
		
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
	
	public User selectUser(String id) throws Exception{
		Connection conn = ds.getConnection();
		
		String sql = "SELECT * FROM usedhunter.user_info where id=?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, id);
		
		ResultSet rs = pstmt.executeQuery(); // select에 사용
		if(rs.next()) {
			User user = new User();
			user.setId(rs.getString(1));
			user.setPwd(rs.getString(2));
			user.setName(rs.getString(3));
			user.setEmail(rs.getString(4));
			user.setBirth(new Date(rs.getDate(5).getTime())); // util.date 를 sql.date 로 변환
			user.setSns(rs.getString(6));
			user.setReg_date(new Date(rs.getTimestamp(7).getTime())); // util.date 를 sql.date 로 변환
			
			return user;
		}
		return null;
	}
	
	
	private void deleteAll() throws Exception{
		Connection conn = ds.getConnection();


		String sql = "delete from `usedhunter`.`user_info`";

		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상

		pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
	}
	

	@Test
	public void main() throws Exception{
//		ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
//	      DataSource ds = ac.getBean(DataSource.class);

	      Connection conn = ds.getConnection(); // 데이터베이스의 연결을 얻는다.

	      System.out.println("conn = " + conn);
	      assertTrue(conn!=null); // 괄호 안의 조건식이 true면 테스트 성공, 아니면 실패
	}
}

 

 

 

deleteUser() 메서드 만들기

 

package com.jcy.usedhunter;

import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jcy.usedhunter.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class DBConnectionTest2Test{
	
	@Autowired
	DataSource ds;
	
	
	@Test
	public void insertUserTest() throws Exception{
		deleteAll();
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		int rowCnt = insertUser(user);
		
		assertTrue(rowCnt==1);
		
	}
	
	@Test
	public void selectUserTest() throws Exception {
		deleteAll();
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		insertUser(user);
		User user2 = selectUser("asdf");
		
		assertTrue(user2.getId().equals("asdf"));
	}
	
	@Test
	public void deleteUserTest() throws Exception{
		deleteAll();
		int rowCnt = deleteUser("asdf");
		assertTrue(rowCnt==0);
		
		User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
		insertUser(user);
		
		int rowCnt2 = deleteUser("asdf");
		assertTrue(rowCnt2==1);
		assertTrue(selectUser(user.getId())==null);
	}
	
	
	// 사용자 정보를 user_info 테이블에 저장하는 메서드
	public int insertUser(User user) throws Exception{
		Connection conn = ds.getConnection();
		
//		INSERT INTO `usedhunter`.`user_info`(`id`,`pwd`,`name`,`email`,`birth`,`sns`,`reg_date`)
//		VALUES('asdf2','1234','smith','aaa@aaa.com','2021-01-01','facebook',now());
		
		String sql = "INSERT INTO `usedhunter`.`user_info` VALUES(?, ?, ?, ?, ?, ?, now())";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getPwd());
		pstmt.setString(3, user.getName());
		pstmt.setString(4, user.getEmail());
		pstmt.setDate(5, new java.sql.Date(user.getBirth().getTime())); // util.Date 인 user.getBirth() 를 sql.Date 로 변환
		pstmt.setString(6, user.getSns());
		
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
	
	public User selectUser(String id) throws Exception{
		Connection conn = ds.getConnection();
		
		String sql = "SELECT * FROM usedhunter.user_info where id=?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, id);
		
		ResultSet rs = pstmt.executeQuery(); // select에 사용
		if(rs.next()) {
			User user = new User();
			user.setId(rs.getString(1));
			user.setPwd(rs.getString(2));
			user.setName(rs.getString(3));
			user.setEmail(rs.getString(4));
			user.setBirth(new Date(rs.getDate(5).getTime())); // util.date 를 sql.date 로 변환
			user.setSns(rs.getString(6));
			user.setReg_date(new Date(rs.getTimestamp(7).getTime())); // util.date 를 sql.date 로 변환
			
			return user;
		}
		return null;
	}
	
	public int deleteUser(String id) throws Exception {
		Connection conn = ds.getConnection();
		String sql = "delete from user_info where id=?";
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, id);
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
	
	
	private void deleteAll() throws Exception{
		Connection conn = ds.getConnection();


		String sql = "delete from `usedhunter`.`user_info`";

		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상

		pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
	}
	

	@Test
	public void main() throws Exception{
//		ApplicationContext ac = new GenericXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/**/root-context.xml");
//	      DataSource ds = ac.getBean(DataSource.class);

	      Connection conn = ds.getConnection(); // 데이터베이스의 연결을 얻는다.

	      System.out.println("conn = " + conn);
	      assertTrue(conn!=null); // 괄호 안의 조건식이 true면 테스트 성공, 아니면 실패
	}
}

 

 

update() 메서드 만들기

// 매개변수로 받은 사용자 정보로 user_info 테이블을 update 하는 메서드
public int updateUser(User user) throws Exception{
		Connection conn = ds.getConnection();
		
		String sql = "UPDATE user_info SET pwd=?, name=?, email=?, birth=?, sns=? Where id=?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql); // SQL injection 방어에 유리, 성능 향상
		pstmt.setString(1, user.getPwd());
		pstmt.setString(2, user.getName());
		pstmt.setString(3, user.getEmail());
		pstmt.setDate(4, new java.sql.Date(user.getBirth().getTime())); // util.Date 인 user.getBirth() 를 sql.Date 로 변환
		pstmt.setString(5, user,getSns()); 
		pstmt.setString(6, user.getId());
		
		int rowCnt = pstmt.executeUpdate(); // 영향 받은 로우행 개수 반환, insert, delete, update 에 사용
		return rowCnt;
	}
@Test
public void updateUserTest() throws Exception{
	deleteAll();
    User user = new User("asdf", "1234", "adb", "aaa@aaa.com", new Date(), "facebook", new Date());
    int rowCnt = insertUser(user);
    assertTrue(rowCnt==1);
    
    User user2 = new User("asdf", "5678", "zzz", "bbb@bbb.com", new Date(), "kakao", new Date());
    rowCnt = updateUser(user2);
    assertTrue(rowCnt==1);
    
    assertTrue(selectUser("asdf").getName().equals("zzz"));
}

 

복사했습니다!