LoginSignup
0
0

GitHub Actions を使用して Kotest の自動実行を行う

Last updated at Posted at 2023-10-08

はじめに

個人開発で使用しているリポジトリに自動テストを導入したため、リポジトリへのプッシュが
行われた際にテストの自動実行を導入する方法を説明します。

実行環境

  • 言語:Kotlin 1.9.0
  • ビルドツール:Gradle 8.3
  • テストフレームワーク:Kotest 5.7.2
  • IDE:Intellij IDEA Community Edition 2023.1.2

想定する読者

基本的には手順の説明のみとなります。
KotlinやKotest、GitHub Actions について知りたい方は他の記事や公式をご覧ください。

  • Kotlin の基本的な内容を理解している方
  • Kotest の導入方法を知りたい方
  • Kotlin に Kotest を導入する方法を知りたい方
  • テストを自動化したい方

リポジトリ

今回説明する内容を実装したリポジトリは以下となります。

実行環境の構築

準備

  • GitHub でリポジトリを作成します

  • Intellij IDEA からクローンし、以下の のコマンドを実行します
    gradle init --type kotlin-application

ソースコードの修正

  • App.ktを以下の通りに修正します
    計算を行うCalcクラスを作成し、足し算を行う関数を作成します。
    main()関数からはCalcクラスのインスタンスを生成し、add()関数を呼び出す
    シンプルなプログラムです。
/*
 * This Kotlin source file was generated by the Gradle 'init' task.
 */
package kotest.ci.sample

/**
 * 計算クラス
 */
class Calc(
    private val num1: Int,
    private val num2: Int
) {
    /**
     * num1 と num2 を加算します。
     *
     * @return num1 と num2 の加算の結果
     */
    fun add(): Int {
        return num1 + num2
    }
}

fun main() {
    val calc = Calc(1, 1)
    print("1 + 1 = ${calc.add()}")
}
  • build.gradle.kts を修正して Kotest を導入します
    修正後、gradle build のコマンドを実行して修正を反映させます
// dependenciesの修正
dependencies {
    testImplementation("io.kotest:kotest-runner-junit5-jvm:5.7.2")
} 

// Kotest junit5ランナーの依存関係を追加
tasks.named<Test>("test") {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}
  • AppTest.ktを以下の通り修正します
/*
 * This Kotlin source file was generated by the Gradle 'init' task.
 */
package kotest.ci.sample

import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe


class AppTest : FunSpec() {
    init {
        context("正常系") {
            val calc = Calc(1, 1)
            calc.add() shouldBe 2
        }
    }
}

  • gradle test コマンドを実行しテストが正常に終了することを確認しておきます

GitHub Actions のジョブを作成

  • .github/workflows ディレクトリを作成します
  • .github/workflowskotest-ci-sample.yaml を作成します
name: kotest-ci-sample

on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up JDK 19
        uses: actions/setup-java@v3
        with:
          java-version: '19'
          distribution: 'temurin'
          cache: 'gradle'

      - name: Grant gradle permission
        run: chmod +x ./gradlew

      - name: Run test
        run: ./gradlew test

準備はここまでです。

ジョブの実行

この時点でリポジトリでプッシュすると、作成したジョブが実行されるようになります。
git push した後に GitHub の Actions を確認してみます。

image.png

うん、無事に正常終了してますね。

最後に

今回初めてGitHub Actions を使用しましたが、感想としては想像以上に簡単に導入できるな、というのが正直なところです。
もう少しややこしいものかと思っていましたが、何でもやってみるものですね。

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