Search code examples
javajunitmockmvc

MockMVC - How to test post to an endpoint without having mockMvc make the actual post?


I have a REST endpoint I'd like to test. Hitting this endpoint via a POST request uploads a file in a remote git repo. I'm trying to test POST calls to this endpoint using mockMvc (I only want to see a return status "isOk()") -- I don't want the endpoint actually being hit by my jUnits, as that would cause unecessary files to be uploaded to the repo and will need to be cleaned up later.

My problem is, mockMvc is making the actual POST call to the endpoint! wth! I thought this was all being mocked?! Is is possible to have mockMvc return isOk() without making the actual call to the endpoint and pushing files to my remote repo?


Solution

  • Mock MVC is only a tool to make it possible to call the methods marked with @GetMapping, @PostMapping, etc.

    The post method from the controller is actually the method that you need to test and it should not be mocked, that's why you hit the real endpoint.

    I suggest you to restructure your controller in the way that the post method will only delegate the job of sending a request to a service. That way your controller will have only one line of code (service call) and at the same time you'll be able to mock the service so that it doesn't hit the real endpoint.