iBatis 환경에서 DB 유닛 테스트를 위한 팁

최근에는 새로운 기능을 개발할 때 test case를 먼저 작성하는 경우가 많다. 특히 DB와 연동되는 기능을 개발할 경우 다양한 종류의 실수로 작업이 지연될 수 있기 때문에 unit test를 꼭 먼저 작성하고 개발을 시작한다.

하지만 일반적인 개발환경에서 테스트 데이터가 DB에 직접 쌓이게 되면 데이터가 꼬이는 경우가 발생할 수 있어서 이를 해결할 방법이 필요하다. 예를 들어 게시판에 글을 쓰고, 수정하고, 지우는 기능을 테스트하면서 오류로 글이 지워지지 않고 남는 경우가 있을 수 있고, 새로운 데이터를 입력하는 테스트인 경우 unique key 제한에 걸려 매번 테스트 데이터를 수정해야 하는 불편함이 따를 수 있다.

이 문제를 피해가기 위해 여러가지 방법을 활용할 수 있는데 Spring에서는 AbstractTransactionalSpringContextTests와 같은 방식으로 이를 해결하고 있다. iBatis 환경에서는 다음과 같이 JUnit4의 기능을 활용해서 DB unit test를 편하게 할 수 있다.

public class TransactionalTestCase {

  @BeforeClass
  public static void create() {
    SqlMapClient.startTransaction();
  }

  @AfterClass
  public static void destroy() {
    SqlMapClient.endTransaction();
  }

  protected ResultSet executeQuery(String sql) throws SQLException {
    Connection conn = SqlMapClient.getConnection();
    Statement st = conn.createStatement();
    return st.executeQuery(sql);
  }

  protected int executeUpdate(String sql) throws SQLException {
    Connection conn = SqlMapClient.getConnection();
    Statement st = conn.createStatement();
    return st.executeUpdate(sql);
  }

  protected int countTableRows(String tableName) throws SQLException {
    int count = 0;
    ResultSet rs = executeQuery("select count(*) from " + tableName);
    while (rs.next()) {
      count = rs.getInt(1);
    }
    return count;
  }

  protected void deleteTable(String tableName) throws SQLException {
    executeUpdate("delete from " + tableName);
  }
}

기본적으로 클래스의 시작과 끝에 Transaction을 걸어주고 있고, 데이터 초기화 기능 및 간단한 테이블 조회 기능을 추가했다. 각자의 환경에 따라 세부적인 코드는 변할 수 있겠지만 이 코드를 바탕으로 쉽게 DB unit test를 할 수 있는 기회가 될 수 있기를 바란다.

This entry was posted in Java and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>