kotlin + Spring boot 中的单元测试休息控制器

Avv*_*Avv 4 junit unit-testing mockito kotlin spring-boot

编辑:我创建了另一个类“Utils”并将函数移动到该类。

class Utils {
fun isMaintenanceFileExist(maintenanceFile: String) : Boolean {
    /** method to check maintenance file, return True if found else False. */
    return File(maintenanceFile).exists()
}
}
Run Code Online (Sandbox Code Playgroud)

我正在测试 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()
    }
Run Code Online (Sandbox Code Playgroud)

但我没有得到预期的结果。

控制器代码:

{
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)
}
...
}
Run Code Online (Sandbox Code Playgroud)

我想从测试中的 isMaintenanceFileExist() 方法返回 true 并想检查 badRequest。请指导如何实现这一点。

Mic*_*sel 7

通过查看您的代码片段,我猜您实际上并没有在测试中使用模拟的 Controller 实例。控制器由 Spring Boot 测试运行程序实例化,而不是使用您的模拟实例。

我建议将该isMaintenanceFileExist方法提取到一个单独的 bean 中,然后使用@MockBean.

控制器和实用程序 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()
}
Run Code Online (Sandbox Code Playgroud)

测试班

@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)
    }

}
Run Code Online (Sandbox Code Playgroud)

第 44.3.7 章