Tran Thang
12/25/2022, 3:08 AMclass 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:
@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 UnitTestRiccardo Lippolis
12/25/2022, 8:28 AMfranztesca
12/25/2022, 10:01 AMcoEvery { ... }
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.gildor
12/27/2022, 4:49 AMgildor
12/27/2022, 4:50 AM