简体   繁体   English

MockMVC - 如何在没有 mockMvc 进行实际发布的情况下测试发布到端点?

[英]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.我有一个要测试的 REST 端点。 Hitting this endpoint via a POST request uploads a file in a remote git repo.通过 POST 请求命中此端点会上传远程 git 存储库中的文件。 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.我正在尝试使用 mockMvc 测试对此端点的 POST 调用(我只想看到返回状态“isOk()”)——我不希望端点实际被我的 jUnit 命中,因为这会导致不必要的文件上传到仓库,稍后需要清理。

My problem is, mockMvc is making the actual POST call to the endpoint?我的问题是,mockMvc 正在对端点进行实际的 POST 调用吗? 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?是否可以让 mockMvc 返回 isOk() 而无需实际调用端点并将文件推送到我的远程仓库?

Mock MVC is only a tool to make it possible to call the methods marked with @GetMapping , @PostMapping , etc. Mock MVC只是一个工具,可以用来调用标有@GetMapping@PostMapping等的方法。

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. 控制器中的post方法实际上是您需要测试的方法,并且不应对其进行模拟,这就是为什么要使用真正的端点了。

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. 我建议您以post方法将只委派向服务发送请求的工作的方式重组控制器。 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. 这样,您的控制器将只有一行代码(服务调用),并且同时您将能够模拟该服务,以便它不会到达真正的端点。

You could also use @MockBean to mock the service, this way it will not do any real calls, hope this helps to anyone who gets same issue in the future.您也可以使用@MockBean 来模拟该服务,这样它就不会进行任何实际调用,希望这对将来遇到同样问题的任何人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM