How to mock a suspend function on an existing mock object?
See original GitHub issueI have mock A
built and given to me. Now, I need to mock a suspend API to return a value foo
.
Example:
@Inject lateinit var mockA: A // using dagger to provide mocks configured in a separate module.
@Test
fun test1() = runBlocking {
// how do i mock a suspend method on mockA?
}
_Originally posted by @andrewborba10 in https://github.com/nhaarman/mockito-kotlin/issues/269#issuecomment-429467218_
Issue Analytics
- State:
- Created 5 years ago
- Reactions:6
- Comments:14 (3 by maintainers)
Top Results From Across the Web
In kotlin, how do I mock a suspend function that wraps a ...
Mock your object, lets name it myObject (myObject has suspend method named isFoo). then: myObject.stub { onBlocking { isFoo() }.doReturn(true) }.
Read more >Coroutines and suspend functions | Mocking | MockK Guidebook
Using coEvery, coVerify, and more to mock coroutines. ... MockK uses function literals to create stubs, small changes are needed to stub suspend...
Read more >Mocking Coroutines - ProAndroidDev
As you can see testing functionality, that is built with Coroutines adds a bit of complexity: suspend functions can't just be called from...
Read more >Testing Kotlin coroutines on Android
This guide covers how suspending functions can be tested, the testing constructs you need to be familiar with, and how to make your...
Read more >MockK | mocking library for Kotlin
Provides DSL to mock behavior. Built from zero to fit Kotlin language. Supports named parameters, object mocks, coroutines and extension function mocking.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
With mockito-kotlin:2.1.0 :
I’m not entirely sure though.
I know this comment will probably be considered unhelpful, but I recently spent a lot of time trying to do the same thing and I eventually came to the conclusion that, assuming no actual business logic is is taking place in your async block/function, I don’t really get anything out of including it in my tests. Testing that a mocked class returns the mocked data that I mocked for it isn’t actually useful.
That is to say, my suspend functions are only there to retrieve data (network calls) and I should focus on testing the function that contains the business logic for once those calls are returned.
Granted, if there is a way to do what you’re asking for it can still be very useful and I want to know.