Spring FrameworkのUnitテスト実装方法 1-2.Repositoryテスト(Junit4, spring-test)

Spring FrameworkのUnitテスト実装方法 1-2.Repositoryテスト(Junit4, spring-test)

Spring FrameworkのUnitテスト実装方法 1-2.Repositoryテスト(Junit4, spring-test)

【サンプルソース】
TERASOLUNA Server Framework for Java (5.x) Development Guideline
サンプルソースはこちら
(これのMyBatis3を使用したパターンで作成してます。)

1-2.Repositoryテスト Junit4,Spring-testライブラリを使用したパターン

1-1とソースの流れは同じですが、データのセットアップ方法が違います。
今回は@sqlアノテーションを使用してsqlファイルからデータをセットアップしてます。
ただ、@sqlでできるのはデータのセットアップ等の事前準備系の処理であり、
テスト後のデータ検証ではJdbcTemplateを使用しています。

【pom.xml】

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

【テスト対象クラス】

TodoRepository.java
テスト対象はupdateメソッド

public interface TodoRepository {
   Todo findOne(String todoId);

    Collection<Todo> findAll();

    void create(Todo todo);

    boolean update(Todo todo);

    void delete(Todo todo);

    long countByFinished(boolean finished);
}

【テストクラス】

TodoRepositoryTestVerSql.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:META-INF/spring/test-context.xml"})
@Transactional
public class TodoRepositoryTestVerSql {

    @Inject
    TodoRepository target;
    
    @Inject
    JdbcTemplate jdbctemplate;
    
    @Before
    public void setUp() throws Exception {
        //@sqlアノテーションで指定したsqlファイルによってセットアップを実行するため、処理なし
    }
    
    @Test
    @Rollback
    //@sqlアノテーションでsqlファイルを呼び出してセットアップする。
    @Sql("classpath:database/test_data.sql")
    public void testUpdate() throws Exception {
        //テスト用のデータを作成
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String todoId = "cceae402-c5b1-440f-bae2-7bee19dc17fb";
        Todo testDataTodo = getTodoData(todoId);
        testDataTodo.setFinished(true);
        
        //updateメソッドのテスト
        boolean actTodo = target.update(testDataTodo);
        
        //結果検証
        assertEquals(actTodo, true);
        
        //期待値の作成
        Todo exptodo = new Todo();
        exptodo.setTodoId("cceae402-c5b1-440f-bae2-7bee19dc17fb");
        exptodo.setTodoTitle("one");
        exptodo.setFinished(true);
        String strDate = "2017-10-01 15:39:17.888";
        Date date = sdFormat.parse(strDate);
        exptodo.setCreatedAt(date);
        
        //処理後データの取得(getTodoDataメソッドはDBからテスト後に変更されたデータを取得するprivateメソッド)
        Todo actTestDataTodo = getTodoData(todoId);
        
        //メソッド実行後テーブルデータ検証
        //date型の表示形式が異なるため、時刻文字列に変換して比較している
        assertEquals(exptodo.getTodoId(), actTestDataTodo.getTodoId());
        assertEquals(exptodo.getTodoTitle(), actTestDataTodo.getTodoTitle());
        assertEquals(exptodo.isFinished(), actTestDataTodo.isFinished());
        assertEquals(sdFormat.format(exptodo.getCreatedAt()) ,sdFormat.format(actTestDataTodo.getCreatedAt()));
    }
}

@Beforeの事前準備のセットアップ部分の記載がなくなったので、その分コードがすっきりしました。
あとここには記載してないですが、テーブルデータの作成用メソッドも不要になってます(sqlファイルに外だししたため)
@sqlはクラス単位、メソッド単位の指定が可能です。

【その他設定】

test-context.xml
jdbctemplateを設定してます

<!-- jdbcTemplateの設定 -->
<bean class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource" />
</bean>

test_data.sql

/* define the schemas. */
CREATE TABLE IF NOT EXISTS todo (todo_id VARCHAR(36) PRIMARY KEY, todo_title VARCHAR(30), finished BOOLEAN, created_at TIMESTAMP);
DELETE FROM todo;

/* load the records. */
INSERT INTO todo (todo_id, todo_title, finished, created_at) VALUES ('cceae402-c5b1-440f-bae2-7bee19dc17fb', 'one', false, '2017-10-01 15:39:17.888');
INSERT INTO todo (todo_id, todo_title, finished, created_at) VALUES ('5dd4ba78-ff5b-423b-aa2a-a07118aeaf90', 'two', false, '2017-10-01 15:39:19.981');
INSERT INTO todo (todo_id, todo_title, finished, created_at) VALUES ('e3bdb9af-3dde-40b7-b5fb-4b388567ab45', 'three', false, '2017-10-01 15:39:28.437');
commit;

DB上にテーブルがなければテーブルの作成からやってます。

DBunitなどのセットアップ用のライブラリを使わない時のセットアップ方法としていいかもしれません。

サンプルソースはgithubで公開してます。
Spring-Unit-Test-pattern2

Junitカテゴリの最新記事