Kotlin Unit Testing Examples

This repository contains examples of basic unit tests written in Kotlin. In specific directories you can find gradle buildscript with needed dependencies and configuration, simple unit test and parameterized test.

All sample projects was verified under Gradle 4.10.2 and Intellij IDEA 2018.2.4

Application

UseCase which provides empty string - to showcase structure of test methods

DistanceConverter - converts meters to kilometers in parameterized tests

MVP - Model-View-Presenter contract

Gradle, Kotlin & Groovy

This Gradle project is by default configured with Gradle’s Kotlin DSL

The equivalent Groovy build are still available for you copy&pasting pleasures, they have been renamed as build.gradle.groovy

You can switch between Groovy and Kotlin by running the script $ ./toggle-kotlin-groovy.sh

Junit4

Attach to project

dependencies{
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Junit5

Attach to project

dependencies {
    testCompile('org.junit.jupiter:junit-jupiter-api:5.3.1')
    testCompile('org.junit.jupiter:junit-jupiter-params:5.3.1')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.3.1')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

KotlinTest

Attach to project

dependencies{
    testCompile 'io.kotlintest:kotlintest-runner-junit5:3.1.10'
}

Spek

Attach to project

repositories {
    mavenCentral()
    maven { url "https://dl.bintray.com/spekframework/spek-dev" }

}

test {
    useJUnitPlatform {
        includeEngines 'spek2'
    }
}

dependencies {
    testImplementation ('org.spekframework.spek2:spek-dsl-jvm:2.0.0-rc.1')  {
        exclude group: 'org.jetbrains.kotlin'
    }
    testRuntimeOnly ('org.spekframework.spek2:spek-runner-junit5:2.0.0-rc.1') {
        exclude group: 'org.junit.platform'
        exclude group: 'org.jetbrains.kotlin'
    }

    testCompile('org.junit.jupiter:junit-jupiter-api:5.3.1')


    // spek requires kotlin-reflect, can be omitted if already in the classpath
    testRuntimeOnly "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}

For Spek you may also need additional Intellij or Android Studio plugin

Mockito

Add to project

repositories {
    mavenCentral()
    jcenter()
}


dependencies {
    testCompile "org.mockito:mockito-core:2.23.0"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Mockito-Kotlin

Add to project

repositories {
    mavenCentral()
    jcenter()
}


dependencies {
    testCompile "org.mockito:mockito-core:2.23.0"
    testCompile "com.nhaarman.mockitokotlin2:mockito-kotlin:2.0.0-RC1"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Mockk

Add to project

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testImplementation "io.mockk:mockk:1.8.12"
}

Strikt

Add to project

dependencies {
    testImplementation("io.strikt:strikt-core:0.17.0")
}