DEV Community

Cover image for Tests Everywhere - Kotlin
Roger Viñas Alcon
Roger Viñas Alcon

Posted on • Edited on

Tests Everywhere - Kotlin

GitHub logo rogervinas / tests-everywhere

🤠 Tests, Tests Everywhere!

Kotlin testing this simple Hello World with Kotest and MockK

Show me the code

Implementation

  1. Create HelloMessage class in HelloMessage.kt:
class HelloMessage {
  val text: String = "Hello World!"
}
Enter fullscreen mode Exit fullscreen mode

We can create it as a class as MockK is able to mock final classes.

  1. Same way create HelloConsole class in HelloConsole.kt:
class HelloConsole {
  fun print(text: String) {
    println(text)
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create HelloApp class in HelloApp.kt:
class HelloApp(private val message: HelloMessage, private val console: HelloConsole) {
  fun printHello() {
    console.print(message.text)
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create main class in Main.kt that wraps it all together:
fun main() {
  val message = HelloMessage()
  val console = HelloConsole()
  val app = HelloApp(message, console)
  app.printHello()
}
Enter fullscreen mode Exit fullscreen mode

Test

Following Kotest > Writing Tests and MockK > Class mock guides ...

  1. Test HelloMessage in HelloMessageTest.kt:
class HelloMessageTest : DescribeSpec({

  describe("HelloMessage") {
    it("should return hello world") {
      val message = HelloMessage()
      message.text shouldBe "Hello World!"
    }
  }
})
Enter fullscreen mode Exit fullscreen mode
  1. Test HelloApp in HelloAppTest.kt:
class HelloAppTest : DescribeSpec({

  describe("HelloApp") {
    it("should print hello message") {
      val messageText = "Hello Test!"

      // 2.1 Create a mock of HelloMessage
      val message = mockk<HelloMessage>()
      // 2.2 Return "Hello Test!" whenever text is called
      every { message.text } returns (messageText)

      // 2.3 Create a mock of HelloConsole
      val console = mockk<HelloConsole>()
      // 2.4 Do nothing whenever print is called
      every { console.print(any()) } just Runs

      // 2.5 Create a HelloApp, the one we want to test, passing the mocks
      val app = HelloApp(message, console)
      // 2.6 Execute the method we want to test
      app.printHello()

      // 2.7 Verify HelloConsole mock print() method
      // has been called once with "Hello Test!"
      verify { console.print(messageText) }
    }
  }
})
Enter fullscreen mode Exit fullscreen mode
  1. Test output should look like:
> Task :test

org.hello.HelloAppTest > HelloApp > should print hello message PASSED

org.hello.HelloMessageTest > HelloMessage > should return hello world PASSED

BUILD SUCCESSFUL in 3s
Enter fullscreen mode Exit fullscreen mode

Happy Testing! 💙

Top comments (0)