rogervinas / tests-everywhere
🤠 Tests, Tests Everywhere!
Kotlin testing this simple Hello World with Kotest and MockK
Show me the code
Implementation
- Create
HelloMessage
class in HelloMessage.kt:
class HelloMessage {
val text: String = "Hello World!"
}
We can create it as a class as MockK is able to mock final classes.
- Same way create
HelloConsole
class in HelloConsole.kt:
class HelloConsole {
fun print(text: String) {
println(text)
}
}
- Create
HelloApp
class in HelloApp.kt:
class HelloApp(private val message: HelloMessage, private val console: HelloConsole) {
fun printHello() {
console.print(message.text)
}
}
- 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()
}
Test
Following Kotest > Writing Tests and MockK > Class mock guides ...
- Test
HelloMessage
in HelloMessageTest.kt:
class HelloMessageTest : DescribeSpec({
describe("HelloMessage") {
it("should return hello world") {
val message = HelloMessage()
message.text shouldBe "Hello World!"
}
}
})
- 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) }
}
}
})
- 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
Happy Testing! 💙
Top comments (0)