【发布时间】:2019-03-27 04:15:11
【问题描述】:
编辑:我创建了另一个类“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()
}
但我没有得到预期的结果。
控制器代码:
{
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。 请指导如何实现这一目标。
【问题讨论】:
标签: unit-testing spring-boot junit kotlin mockito