Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock objects in relaxed mode?

Tags:

kotlin

mockk

I have an object

object Foo {
    fun doSomething(param: String) {
        throw Exception()
    }
}

I want it to become a stub (relaxed mock in mockk terminology) in my test.

Other words, I want this test to pass without exception:

@Test 
fun shouldAskFooWithCorrectParams() { 
    mockkObject(Foo) // How to change it to make Foo a stub
    Foo.doSomething("hey!")
    verify(exactly = 1) { Foo.doSomething("hey!") }
}
like image 358
vdshb Avatar asked Oct 28 '25 05:10

vdshb


1 Answers

Additional every { Foo.doSomething(any()) } answers {} does the trick for a single method.

This test is passes:

@Test
fun shouldAskFooWithCorrectParams() {
    mockkObject(Foo) 
    every { Foo.doSomething(any()) } answers {}
    Foo.doSomething("hey!")
    verify(exactly = 1) { Foo.doSomething("hey!") }
}
like image 62
vdshb Avatar answered Oct 30 '25 08:10

vdshb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!