LoginSignup
0
0

More than 3 years have passed since last update.

kotlin+SpringBootでCommandLineRunnerを使う

Last updated at Posted at 2020-07-31

はじめに

Java + SpringBootでコマンドラインアプリを作るためのHow to記事は
Qiitaにもいくつかありますが、こちらはkotlinでやった場合です。

コード

main関数

SampleApplication.kt
@SpringBootApplication
class SampleApplication(val service: SampleService) : CommandLineRunner {
    override fun run(vararg args: String?) {
        // コマンドライン引数から取得
        val name = args[0]!!.toString()
        val mailAddress = args[1]!!.toString()
        service.profileRegister(name, mailAddress)
    }
}

fun main(args: Array<String>) {
    SpringApplication.run(SampleApplication::class.java, *args)
}

テストコード(JUnit5)でrunが動かないようにする設定。
これをやらないとテストコード実施時に、SampleApplicationのrunが動いてしまうようです。
アノテーション@ExtendWith@ContextConfigurationにて定義します。

SampleServiceTest.kt
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [SampleServiceTest::class],
        initializers = [ConfigFileApplicationContextInitializer::class])
class SampleTest {
    @Autowired
    private lateinit var svc: SampleService

    @Test
    fun testProfileRegister() {
            val resp = svc.profileRegister("Taro Yamada", "xxxxx@example.com")
            assertThat(resp.name).isEqualTo("Taro Yamada")
            assertThat(resp.mailAddress).isEqualTo("xxxxx@example.com")
    }
}

参考(Javaの記事です)

Spring Bootで簡単なコマンドラインアプリケーションを作成してみる
https://reasonable-code.com/command-line-runner/

Spring Bootでコマンドラインアプリを作る時の注意点
https://qiita.com/tag1216/items/898348a7fc3465148bc8#comments

SpringBootでのJUnitでCommandLineRunnerが動くことの回避策
https://qiita.com/salkun/items/721125f0deec0a082504

0
0
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
0
0