Mock singleton objects and static methods
Despite the name, object mocks behave more like spies. If a method is not stubbed, then the real method will be called. This differs from regular mocks, where a method will either throw or do nothing if it is not stubbed.
fun add(a: Int, b: Int) {
return a + b
}
}
object Calculator2 {
fun add(a: Int, b: Int) {
return a + b
}
mockkObject(Calculator2)
// throws because the method was not stubbed
println(calculator1.add(2, 2))
// returns the result from the real method
println(Calculator2.add(2, 2))
Sometimes you may end up working with Java code in your tests, which can have static methods.
mockkStatic("com.name.app.Writer")
Rather than passing a reference to the class, you pass the class name as a string. You can also choose to pass in a reference to the class, and MockK will figure out the class name.
If you’d like to revert back to the real object, you can use the unmockkObject
method. This removes any stubbed behaviour you may have added.
object Calculator {
}
}
mockkObject(Calculator)
every { Calculator.add(any(), any()) } returns 10
// prints 10
println(Calculator.add(2, 2))
unmockkObject(Calculator)
println(Calculator.add(2, 2))