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

时间:2013-10-16 17:32:04

标签: java spring testing spring-mvc mocking

我有这个课程进行测试。此测试使用mockMvc对象。我认为这个对象发送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();

        }
...
}

我认为有时我想使用其他配置的控制器。

这是什么意思?

CandidateControllerTest测试CandidateController

的方法
@Controller
CandidateController{

   @Autowire
   CandidateService candidateService;

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

   }

}

我想通过模拟candidateService模拟candidateService已发送的http请求到控制器

真的吗?

1 个答案:

答案 0 :(得分:0)

candidateService课程中的CandidateController创建一个setter。

CandidateControllerTest中,从CandidateController获取WebApplicationContext bean并使用setter设置模拟。

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

我不推荐这个。如果您只是单独测试CandidateController ,那就没关系了。但是你正在MockMvc后面进行测试,这是集成测试。模拟不属于被测试的堆栈。

相关问题