Unit testing kotlin和x2B中的单元测试rest控制器;弹簧靴

Unit testing kotlin和x2B中的单元测试rest控制器;弹簧靴,unit-testing,spring-boot,junit,kotlin,mockito,Unit Testing,Spring Boot,Junit,Kotlin,Mockito,编辑:我创建了另一个类“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并模拟如

编辑:我创建了另一个类“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)
}
...
}
{
utilObj=Utils()
...
@邮戳(“/post”)
趣味registerByMail(@Valid data:RequestData):ResponseEntity
{
//检查维护模式,如果返回为真(错误代码:9001)
如果(utilObj.isMaintenance文件存在(“maintenanceFilePath”)){
println(“----维护文件存在。正在退出。-----”)
var错误=错误响应(响应(响应代码维护、,
ResponseCode.MAINTENANCE.toString())
返回ResponseEntity.badRequest().body(错误)
}
...
}
我想从测试中的IsMaintenance FileExist()方法返回true,并检查badRequest。
请指导如何实现这一点。

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

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

控制器和Util 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()
}

请参阅。

谢谢。我创建了另一个类,但它仍然没有按预期工作。我编辑了上面的内容。抱歉,我对kotlin和spring boot都是初学者。我自己快速编写了场景,并在回答中附加了运行代码。
@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)
    }

}