【问题标题】:Unexpected return code while testing spring controller测试弹簧控制器时出现意外的返回码
【发布时间】:2022-01-05 11:14:24
【问题描述】:

我的应用程序中有简单的 RestController,带有后映射

@PostMapping("/bank/api/balance")
    fun changeBalance(@RequestParam amount: String, @RequestParam action: String)

我有这个控制器的测试功能。

private fun postBalanceAddRequest(amount: String): ResultActions {
        return mockMvc.perform(MockMvcRequestBuilders.post(baseUrl).apply {
            param("action", "add")
            param("amount", amount)
        })
    }

我在这个测试中使用的

@Test
        fun `add post request must return ok if request contains correct data`() {
            Mockito.`when`(authenticationService.getCurrentUserUsername()).thenReturn("user")
            Mockito.`when`(userService.userExist("user")).thenReturn(true)

            postBalanceAddRequest(amount = "10")
                .andExpect(MockMvcResultMatchers.status().isOk)

        }

当我开始这个测试时,我得到了 404 码,但在我看来,这里不可能有这样的返回码。

【问题讨论】:

  • 对不起,我忘了private val baseUrl = "http://localhost:8080/bank/api/balance"

标签: spring rest kotlin testing


【解决方案1】:

当使用MockMvc时,你不需要提供完整的url(包括域和端口),mockMvc 会处理它。
相反,您只需要 uri。将您的 baseUrl 设置为 /bank/api/balance

【讨论】:

  • 但是我在同样的情况下使用完整的 url,它可以工作。无论如何,我尝试使用您的建议并获得 404
【解决方案2】:

感谢您的帮助,我只是忘了添加必要的控制器。至于 mockMvc,你可以使用短 url,没有域和端口 (我认为这是最好的方法),但如果你愿意,你可以使用完整的 url。

【讨论】:

  • 如果您作为答案发布,请您分享更多详细信息。这将在未来对其他人有所帮助!
猜你喜欢
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
相关资源
最近更新 更多