LoginSignup
6
2

More than 3 years have passed since last update.

Kotlin + JUnit 5 で Table Driven Test

Last updated at Posted at 2020-03-19

TL; DR

Go言語のテーブル駆動テストみたいなことをKotlin + JUnit 5でやってみたのでスニペットレベルに近い形で軽くまとめました。

環境

  • Kotlin: 1.3.50
  • Spring boot: 2.1.5.RELEASE
  • JUnit: 5.5.1

テストケースを内部クラスで定義

inner class TestCase(
    val testName: String,
    val paramsMap: Map<String, String>
)

@TestFactory アノテーションでテストケースのインスタンスをStreamで流し込む

@TestFactory
fun test(): Stream<DynamicNode> {
    return Stream.of(
        TestCase(
            testName = "データ取得オフセットの値が0より小さい場合",
            paramsMap = mapOf("limit" to "15", "offset" to "-1")
        ),
        TestCase(
            testName = "記事取得件数が0より少ない場合",
            paramsMap = mapOf("limit" to "-1", "offset" to "0")
        )
    ).map { testCase ->
        DynamicTest.dynamicTest(
            testCase.testName
        ) {
            val queryParams = LinkedMultiValueMap<String, String>()
            queryParams.setAll(testCase.paramsMap)

            mockMvc.perform(
                MockMvcRequestBuilders
                    .get("articles")
                    .params(queryParams)
            )
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity)
                .andReturn()
        }
    }
}

まとめ

APIのクエリパラメータの異常系のテストとかはテーブルドリブンテストでまとめると、テストケースの一覧性があって見やすいので積極的に活用していきたいです。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2