简体   繁体   English

如何使用MockMvc向被模拟的控制器发送http请求?

[英]How to send http request to mocked controller using MockMvc?

I have this class for test. 我有这个课程进行测试。 This test uses mockMvc object. 此测试使用mockMvc对象。 My opinion that this object send http requests and these requests handles controller which configuration takes from pathToFile.xml 我认为这个对象发送http请求,这些请求处理控制器从pathToFile.xml获取配置

    @ContextConfiguration(locations = { "classpath:/pathToFile.xml" })
    @WebAppConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    public class CandidateControllerTest {
        @Autowired
        WebApplicationContext wac;

        MockMvc mockMvc;

        @Before
        public void before() {
           mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();

        }
...
}

I think that sometimes I want use controller with other configuration. 我想有时我想用其他配置控制器。

What does it mean? 这是什么意思?

CandidateControllerTest tests methods of CandidateController class CandidateControllerTest测试CandidateController类的方法

@Controller
CandidateController{

   @Autowire
   CandidateService candidateService;

   @RequestMapping("/path")
   public string handleSomething(Model model){
    ...
      candidateService.doSomething();
    ...
      return "viewName"

   }

}

I want to mock candidateService an sent http requests to controller with mocked candidateService 我想嘲笑candidateService的发送HTTP请求与嘲笑到控制器candidateService

It is really? 真的吗?

Create a setter for the candidateService in your CandidateController class. CandidateController类中为candidateService创建一个setter。

In your CandidateControllerTest , get the CandidateController bean from the WebApplicationContext and use the setter to set the mock. CandidateControllerTest ,从WebApplicationContext获取CandidateController bean并使用setter设置mock。

CandidateService candidateServiceMock = ...; // mock it
CandidateController cc = (CandidateController) wac.getBean(CandidateController.class);
cc.setCandidateService(candidateServiceMock);

I don't recommend this. 我不推荐这个。 If you were simply testing the CandidateController on its own , this would be fine. 如果你只是测试CandidateController 就其本身而言,这将是罚款。 But you are testing it behind the MockMvc , which is integration testing. 但是你正在MockMvc背后进行测试,这是集成测试。 A mock doesn't belong in the stack being tested. 模拟不属于正在测试的堆栈。

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

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