Kotlinx.coroutines: How to test kotlin suspend function from spock

Created on 17 Feb 2020  路  3Comments  路  Source: Kotlin/kotlinx.coroutines

Hi,

I haven't found a way until now to unit test a suspend function using spock.
If anyone can shed some light on this please do so.
Thanks

question

Most helpful comment

You could also mock that Continuation object, which kotlin is compiling into the method call. This code worked for me:

// mocked continuation
def continuation = Mock(Continuation) {
  getContext() >> Mock(CoroutineContext)
}

// method call which should be tested
subjectUnderTest.suspendableMethod(someParameter, continuation)

All 3 comments

You can try calling your suspending function from runBlocking { ... } and then testing the result of that.

I cannot use runBlocking from spock, however this is a good idea. I could create a wrapper kotlin function with runBlocking{}. Thanks, I'll try.

You could also mock that Continuation object, which kotlin is compiling into the method call. This code worked for me:

// mocked continuation
def continuation = Mock(Continuation) {
  getContext() >> Mock(CoroutineContext)
}

// method call which should be tested
subjectUnderTest.suspendableMethod(someParameter, continuation)
Was this page helpful?
0 / 5 - 0 ratings