好的..所以解决方案最终是由您自己提出的..您猜对了..阅??读文档:/
http://docs.spring.io/spring-framework/docs/3.2.0.BUILD- SNAPSHOT/reference/htmlsingle/#spring-mvc-test- framework
此外,您可以通过Spring配置将模拟服务注入到控制器中,以便专注于测试Web层。
因此,最终的解决方案如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"testContext.xml","../path/to/applicationContext.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class MyControllerTest {
private mockmvc mockmvc;
@Autowired
private WebApplicationContext wac;
@Autowired
private MyService myService;
@Before
public void setup() {
this.mockmvc = mockmvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void mytest() {
MyRequest request = new MyRequest();
MyResponse response = new MyResponse();
String expectedValue = "foobar";
Mockito.when(myService.doSomething((MyRequest) Mockito.any())).thenReturn(response);
MockHttpServletRequestBuilder builder = mockmvcRequestBuilders.post("/myendpoint");
String request = IoUtils.toString(context.getResource("classpath:/request.json").getURI());
builder.content(request);
builder.contentType(MediaType.APPLICATION_JSON);
mockmvc.perform(builder)
.andExpect(mockmvcResultMatchers.status().isOk())
.andExpect(mockmvcResultMatchers.jsonPath("$.someKey").value(expectedValue));
Mockito.verify(myService, Mockito.times(1)).doSomething((MyRequest) Mockito.any());
}
}
然后,您只需为此测试定义一个上下文文件,testContext.xml
其中包含服务对象的模拟:
<bean id="myService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.mypackage.MyService"/>
</bean>
重要的是,MyService实例已@Autowired
进入测试,因此可以进行编排。
这允许您模拟出您喜欢的任何实例,无论它们是否在服务类,方面等中,只要您适当地命名Bean。因此,在这种情况下,MyService
将声明为:
@Component("myService")
public class MyService {
...