Exercising Java code from Kotlin

Another means of using tests to exercise and improve interop between Java and Kotlin is to use Kotlin code to test our Java code and vice versa. By using Kotlin to test Java, we can test more efficiently by taking advantage of Kotlin features such as data classes and the Kotlin standard library.

To explore this testing interplay between Java and Kotlin, let's walk through an example. Here, we've created a simple Java class called StudentPresenter:

public class StudentPresenter {

private List<Student> students;

public StudentPresenter(List<Student> students) {
students.sort(Comparator.comparing(Student::getLastName));

this.students = students;
}

public List<Student> getStudents() {
return students;
}
}

We can write a test in Kotlin to validate that the students field is properly sorted:

@Test
fun `test students are sorted correctly`() {
val presenter = StudentPresenter(
listOf(
Student("Nate", "Ebel"),
Student("Jane", "Doe"),
Student("John", "Smith")
)
)

val sortedStudents = presenter.students

assertEquals(sortedStudents[0], Student("Jane", "Doe"))
}

With this test written in Kotlin, we are able to quickly pass in our list of Student objects by using the listOf() function. We can quickly validate our expected value by taking advantage of the Student data class that has the equals() function generated for us, thereby making comparisons easy.

Testing this same code from Java would have required a good deal more boilerplate code. By leveraging helper functions such as listOf() and language features such as data classes, our test code starts to become more concise, easier to read, and easier to maintain.