If you are looking for a mock framework for Kotlin tests, Mockk is definitely on first on the list. I wrote my first test following a simple example on the official website (https://mockk.io/#dsl-examples). In my case, I am testing an export class using a parser to deserialize a file into an object:
@Test fun `test export excluding sub-folders`() { // given val path = "my/new/path" val parser = mockk() every { parser.buildObject("$path/data.xml") } returns MyObject("first name", "last name", "title", "manager") // when var myObject = exporter.parse( parser, getResourceFile(path), mutableListOf() ) // then verify { parser.buildObject("$path/data.xml") } confirmVerified(parser) // verifies all the verify calls were made assertEquals("first name", myObject.firstName) assertEquals("last name", myObject.lastName) assertEquals("title", myObject.title) assertEquals("manager", myObject.manager) }
Wunderbar! I ran my test… and it failed:
java.lang.NoClassDefFoundError: Could not initialize class io.mockk.impl.JvmMockKGateway
What in the world is that?! I checked my pom file and verified I had the latest version:
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk</artifactId>
<version>1.9.3</version>
<scope>test</scope>
</dependency>
After a while, I figured out the issue resides in the IDE (https://github.com/mockk/mockk/issues/254). Mockk has issue when running on JDK 11. I went to Intellij IDEA -> File -> Project Structure, and changed the Project SDK to JDK 8 (which I use for my current project). You can probably find another version that would work for your own project.
