UserDaoTest를 실행하기 전 DB의 User 정보를 모두 삭제해야 함
—> 외부 상태에 따라 성공/실패 여부가 나뉘기 때문에 동일한 결과가 나오도록 해야 함.
public void deleteAll() throws SQLException{
Connection c = dataSource.getConnection();
PreparedStatement ps = c.preparedStatement("delete from users");
ps.executeUpdate();
ps.close();
c.close();
}
public int getCount() throws SQLException{
Connection c = dataSource.getConnection();
PreparedStatement ps = c.preparedStatement("select count(*) from users");
Result res = ps.executeQuery();
int count = rs.getInt(1);
res.close();
ps.close();
c.close();
return count;
}
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class UserDaoTest{
@Test
public void addAndGet() throws SQLException{
// deleteAll()과 getCount()가 잘 동작하는가?
dao.deleteAll();
assertThat(dat.getCount(), is(0));
ApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml");
UserDao dao = context.getBean("userDao", UserDao.class);
User user = new User();
user.setId("id");
user.setName("name");
user.setPassword("password");
dao.add(user);
// getCount()가 잘 동작하는가?
assertThat(dat.getCount(), is(1));
User user2 = dao.get(user.getId());
//assertThat : 첫 번째 파라미터와 두 번째 파라미터를 matcher 조건으로 비교
//assertThat은 equals와 비슷한 기능을 갖는다.
assertThat(user2.getName(), is(user.getName())); //user와 user2의 name 비교
assertThat(user2.getPassword(), is(user.getPassword())); // user와 user2의 password 비교
}
}