在使用错误管理之前,测试工作正常,但一旦按如下方式包装响应,我就开始得到
no answer found for: PostPreviewRepository(#1).getPosts-qim9Vi0(0, continuation {})
测试的目标方法:
override suspend fun getPosts(page: UInt): Result<List<PostPreviewModel>> {
return try {
val posts = postService.getPosts(page)
Success(postPreviewMapper.fromListDto(posts.body()!!.data))
} catch (e : Exception) {
Failure(HttpError(e))
}
}
映射器
class PostPreviewMapper @Inject constructor(
private val ownerPreviewMapper: OwnerPreviewMapper,
) {
fun fromListDto(postPreviews: List<PostPreviewDTO>): List<PostPreviewModel> =
postPreviews.map { fromDto(it) }
fun fromDto(postPreview: PostPreviewDTO) = PostPreviewModel(
id = postPreview.id,
text = postPreview.text,
imageUrl = postPreview.image,
publishDate = postPreview.publishDate,
owner = ownerPreviewMapper.fromDto(postPreview.owner)
)
}
单元测试
@Test
fun `Given repository returns empty list, When GetPostPreviewsUseCase is invoked, Then returns empty list`() =
runTest {
// Given
coEvery { postPreviewRepository.getPosts(23u) } returns Success(emptyList())
// When
val postsList = getPostPreviewsUseCase.invoke()
// Then
postsList.onSuccess { postsModels ->
assertTrue(postsModels.isEmpty())
}
}
这对我有用:
@Test
fun `Given repository returns empty list, When GetPostUseCase is invoked, Then returns empty list`() =
runTest {
// Given
coEvery { postRepository.getPosts(0) } returns ResultOf.Success(emptyList())
// When
val postsList = getPostUseCase.invoke(0) as ResultOf.Success
// Then
assertTrue(postsList.value.isEmpty())
}