2 Minutes: Studying Kotlin while writing in Java

Simply the best idea I’ve heard last time — using Kotlin to test Java.

It’s brilliant - it gives you a way to have Kotlin in production from the very first day of trying it (I have those tests in Java, I re-write them in Kotlin when I have time, if something goes wrong — I just use Java for now), it creates yet another reason to actually have tests and it doesn’t need much to support.

Module’s build.gradle

apply plugin: 'com.android.application'
apply plugin: "kotlin-android"

android {
//...
    sourceSets {
test.java.srcDirs += 'src/test/kotlin'
}
}

afterEvaluate {
android.sourceSets.all { sourceSet ->
if (!sourceSet.name.startsWith("test"))
{
sourceSet.kotlin.setSrcDirs([])
}
}
}

dependencies {
//...
    //KOTLIN
testCompile "org.jetbrains.kotlin:kotlin-stdlib:$rootProject.kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$rootProject.kotlin_version"
kapt 'com.google.dagger:dagger-compiler:2.9'
testCompile "com.nhaarman:mockito-kotlin:1.3.0"
//...
}

Root build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
ext.kotlin_version = "1.0.6"
repositories {
jcenter()
}
dependencies {
//...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

//...

And here you go.

Kapt’ing Dagger2 and adding Mockito-Kotlin are only required if you use them.


2 Minutes are less-then-one-cigarette, while-brewing-coffee articles about different questions in Android. You can read other ones using tag 2 Minutes. I’m always happy to hear a feedback from you on how to make this thing better and what you’d like to read about.