我有这个课程进行测试。此测试使用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请求到控制器
真的吗?
答案 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
后面进行测试,这是集成测试。模拟不属于被测试的堆栈。