Hello everyone, I have the repository, so i would ...
# coroutines
Hello everyone, I have the repository, so i would like to write UnitTest for the function in this repository. The first time, i am try to write UnitTest use runBlocking but i think it's not good ideal, So
Copy code
class PostsRepositoryImp(private val apiService: ApiService) : PostsRepository {

    override suspend fun getPosts(): List<Post> {
        return apiService.getPosts()

    override suspend fun insertPost(post: Post) {
       Log.e("LOG","UnitTest Success====: "+post.title)
in UnitTest:
Copy code
    fun insertPost() = runBlocking {
        val post = Post(1243, 12, "Test Title", "Test Body")
        every { runBlocking { postsRepository.insertPost(post) } }
        val result = postsRepository.insertPost(post)

        coEvery {

But it's not working with exception. So any help me this problem. Update: I am using MockK to write UnitTest
You could try using the kotlinx-coroutines-test library
You're not using mockk correctly. First, use
coEvery { ... }
and no
every { runBlocking { ... } }
for suspending code. Second,
should be used if you want to stub a certain API call. You should use in combination with a stubbing function like
coEvery { ... } returns 42
) In this case, the function returns Unit so you can use
just Runs
. Third, the assertion part of your test when using a mock should be done using
, not `every/coEvery`: the test should generally have: • setup:
+ stubbed function +
returns/answers/just Runs
. • Method invocation • Assertion:
+ method that you expect to be invoked Fourth, don't overuse mocks. This test looks like a test where you could use a fake implementation of
to make it more resilient. Read about mocks vs fakes, and the problems of overusing mocks.
I don’t see how kotlinx-coroutines-test is helpful here
I feel that it’s exactly the case when you shouldn’t use mocking at all, even though it will work if you follow franztesca advice how to use it correctly. Just implement ApiService with required data, a lot faster (for unit tests) and clear