Home > Enterprise >  Unexpected return code while testing spring controller
Unexpected return code while testing spring controller

Time:11-30

I have simple RestController in my application, with post mapping

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

And I have test function for this controller.

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

Which I am using in this test

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

        }

When I start this test I got 404 code, but it seems to me that there cannot be such a return code here.

CodePudding user response:

when using MockMvc you don't need to provide the full url (including domain and port), the mockMvc will take care of it.
instead, you need just the uri. set your baseUrl to /bank/api/balance

CodePudding user response:

Thanks for help, I make a mistake in mocking service :/

  • Related