编辑:我创建了另一个类“Utils”并将函数移动到该类。
class Utils {
fun isMaintenanceFileExist(maintenanceFile: String) : Boolean {
/** method to check maintenance file, return True if found else False. */
return File(maintenanceFile).exists()
}
}
我正在测试 post API 并模拟如下方法:
@Test
fun testMaintenanceMode() {
val mockUtil = Mockito.mock(Utils::class.java)
Mockito.`when`(mockUtil.isMaintenanceFileExist("maintenanceFilePath"))
.thenReturn(true)
// Request body
val body = "authId=123&email=a@mail.com&confirmationKey=86b498cb7a94a3555bc6ee1041a1c90a"
// When maintenance mode is on
mvc.perform(MockMvcRequestBuilders.post("/post")
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.content(body))
.andExpect(MockMvcResultMatchers.status().isBadRequest)
.andReturn()
}
但我没有得到预期的结果。
Controller 代码:
{
utilObj = Utils()
...
@PostMapping("/post")
fun registerByMail(@Valid data: RequestData) : ResponseEntity<Any>
{
// check for maintenance mode, if True return (error code : 9001)
if(utilObj.isMaintenanceFileExist("maintenanceFilePath")) {
println("-------- Maintenance file exist. Exiting. --------")
var error = ErrorResponse(Response(ResponseCode.MAINTENANCE,
ResponseCode.MAINTENANCE.toString()))
return ResponseEntity.badRequest().body(error)
}
...
}
我想从测试中的 isMaintenanceFileExist() 方法返回 true 并想检查 badRequest。
请指导如何实现这一点。
最佳答案
通过查看您的代码片段,我猜您实际上并没有在测试中使用模拟的 Controller 实例。 Controller 由 Spring Boot 测试运行程序实例化,而不是使用您的模拟实例。
我建议提取 isMaintenanceFileExist
方法转换成一个单独的 bean,然后使用 @MockBean
模拟它.
Controller 和实用程序 Bean
@RestController
class MyController(@Autowired private val utils: Utils) {
@PostMapping("/post")
fun registerByMail(@RequestBody data: String): ResponseEntity<Any> {
if (utils.isMaintenanceFileExist("maintenanceFilePath")) {
println("-------- Maintenance file exist. Exiting. --------")
return ResponseEntity.badRequest().body("error")
}
return ResponseEntity.ok("ok")
}
}
@Component
class Utils {
fun isMaintenanceFileExist(maintenanceFile: String) = File(maintenanceFile).exists()
}
测试类@WebMvcTest(MyController::class)
class DemoApplicationTests {
@MockBean
private lateinit var utils: Utils
@Autowired
private lateinit var mvc: MockMvc
@Test
fun testMaintenanceMode() {
BDDMockito.given(utils.isMaintenanceFileExist("maintenanceFilePath"))
.willReturn(true)
val body = "test"
mvc.perform(MockMvcRequestBuilders.post("/post")
.contentType(MediaType.TEXT_PLAIN)
.content(body))
.andExpect(MockMvcResultMatchers.status().isBadRequest)
}
}
见 chapter 44.3.7 .
关于unit-testing - kotlin + Spring boot 中的单元测试休息 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940334/