我有一個控制器,它根據客戶名稱獲取特定服務:
@RestController
class BasicController(){
@Autowired
private lateinit var services: List<BasicService<*>>
private var service: BasicService<*>? = null
@GetMapping("/{customer}")
fun getAll(@PathVariable customer: String): ResponseEntity<String>{
service = services.getServiceByCustomer(customer)
/... code w/return value .../
}
}
我有一個包含以下內容的檔案 Extensions.kt:
fun <T: BasicService> List<T>.getServiceByCustomer(customer: String): T?{
return this.find{
it::class.simpleName?.contains(customer, ignoreCase = true) == true
}
}
是否可以回傳類似于service何時services.getServiceByCustomer呼叫的模擬 `when`(mock.function(anyString())).thenReturn(value)?
我試過使用 mockK 和以下內容:
mockkStatic("path.to.ExtensionsKt")
every {listOf(service).getServiceByCustomer)} returns service
但我認為我沒有正確使用它......我目前正在使用com.nhaarman.mockitokotlin2但已經嘗試過io.mockk
uj5u.com熱心網友回復:
您只需要使用customer與模擬服務的簡單名稱實際匹配的 。您不需要甚至應該模擬擴展功能。請嘗試以下操作:
class BasicControllerTest {
@MockK
private lateinit var basicService: BasicService
private lateinit var basicController: BasicController
@BeforeEach
fun setUp() {
clearAllMocks()
basicController = BasicController(listOf(basicService))
}
}
此外,請考慮使用建構式注入而不是欄位注入:
@RestController
class BasicController(private val services: List<BasicService<*>>){
private var service: BasicService<*>? = null
@GetMapping("/{customer}")
fun getAll(@PathVariable customer: String): ResponseEntity<String>{
service = services.getServiceByCustomer(customer)
/... code w/return value .../
}
}
最后,考慮使用@WebMvcTest而不是常規單元測驗來測驗控制器。在此處查看更多資訊https://www.baeldung.com/spring-boot-testing#unit-testing-with-webmvctest。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340181.html
上一篇:如何計算按行轉換的sqrt比例?
