unit-testing - kotlin + Spring boot 中的单元测试休息 Controller

标签 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 并模拟如下方法:
@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/

相关文章:

java - 为什么我不能将嵌入式 EJB 容器与我自己的持久性单元一起使用?

laravel - 模拟对同一类中另一个函数的函数调用

java - 如何使用 Java 或 Spring boot 在从 Mongodb 检索的 HTML 中显示图像

java - LocalContainerEntityManagerFactoryBean

java - 用于 Stax 解析器的 Junit

android - 如何使用嵌套的挂起函数对 kotlin 协程进行单元测试

python - 如何测试写入文件的Python函数

spring-boot - 我如何在 Spring Boot-1.4.1-RELEASE 中制作 init-sql

java - @BeforeClass 上的 JUnit 超时

java - 在 Eclipse 中进行 JUnit 测试之前运行外部命令