【发布时间】:2022-11-27 13:02:35
【问题描述】:
我对 MockK 有疑问。
我有一堂课:
@Service
class ItemServiceImpl(private val varPuObjectMapper: VarPuObjectMapper) : OutboundAdvicesService {
override suspend fun getItemsForWarehouse(warehouseId: String): ItemsDTO {
// do stuff
}
override suspend fun getPickingListsForWarehouse(warehouseId: String): PickingListsDTO {
val groupedOutboundAdvices = getItemsForWarehouse(warehouseId)
// do other stuff
}
}
和这个类的测试:
class ItemServiceGroupingTest : FunSpec({
val warehouseId = "1"
val myObjectMapper = MyObjectMapper()
val itemService = mockk<ItemServiceImpl>()
beforeTest {
val items1 = myObjectMapper
.getObjectMapper()
.readValue(Mockups.ITEMS_1, ItemsDTO::class.java)
coEvery {
itemService.getItemsForWarehouse(warehouseId)
} returns items1
}
test("should get items for warehouse with ID 1") {
val itemsDTO = itemService.getItemsForWarehouse(warehouseId)
// assertions here
}
test("should get picking lists for warehouse with ID 1") {
val pickingLists = itemService.getPickingListsForWarehouse(warehouseId)
// assertions here
}
})
现在第一个测试成功通过,但第二个测试失败:
没有找到答案:ItemServiceImpl(#1).getPickingListsForWarehouse(1, continuation {}) io.mockk.MockKException:找不到答案:ItemServiceImpl(#1).getPickingListsForWarehouse(1, continuation {}) 在 app//io.mockk.impl.stub.MockKStub.defaultAnswer(MockKStub.kt:93)
据我了解,这失败是因为
getPickingListsForWarehouse方法没有被模拟。是否可以使用 MockK 调用真正的方法?我尝试使用spyk而不是mockk,我尝试使用mockk和relaxed = true,但它让我无处可去......
【问题讨论】:
标签: unit-testing kotlin mockk kotest