簡體   English   中英

kotlin + Spring boot 中的單元測試休息控制器

[英]Unit test rest controller in 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()
}
}

我正在測試 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。 請指導如何實現這一點。

通過查看您的代碼片段,我猜您實際上並沒有在測試中使用模擬的 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()
}

測試班

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

}

第 44.3.7 章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM