[英]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.