Hello everyone, I have the repository, so i would ...
# coroutines
t
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) {
        apiService.insertPost(post)
       Log.e("LOG","UnitTest Success====: "+post.title)
    }
}
in UnitTest:
Copy code
@Test
    fun insertPost() = runBlocking {
        val post = Post(1243, 12, "Test Title", "Test Body")
        every { runBlocking { postsRepository.insertPost(post) } }
        val result = postsRepository.insertPost(post)

        coEvery {
            postsRepository.insertPost(post)
        }

    }
But it's not working with exception. So any help me this problem. Update: I am using MockK to write UnitTest
r
You could try using the kotlinx-coroutines-test library
f
You're not using mockk correctly. First, use
coEvery { ... }
and no
every { runBlocking { ... } }
for suspending code. Second,
every
,
coEverey
should be used if you want to stub a certain API call. You should use in combination with a stubbing function like
returns
or
answers
(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
verify/coVerify
, not `every/coEvery`: the test should generally have: • setup:
every/coEvery
+ stubbed function +
returns/answers/just Runs
. • Method invocation • Assertion:
verify/coVerify
+ 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
ApiService
to make it more resilient. Read about mocks vs fakes, and the problems of overusing mocks.
g
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