简体   繁体   中英

How to send http request to mocked controller using MockMvc?

I have this class for test. This test uses mockMvc object. My opinion that this object send http requests and these requests handles controller which configuration takes from 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

@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

It is really?

Create a setter for the candidateService in your CandidateController class.

In your CandidateControllerTest , get the CandidateController bean from the WebApplicationContext and use the setter to set the 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. But you are testing it behind the MockMvc , which is integration testing. A mock doesn't belong in the stack being tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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