好的,我们正在谈论 Spring (3.2.0) MVC
我们定义了一个切入点,以“围绕”注释触发,如下所示:
@Around("@annotation(MyAnnotation)")
public void someFunction() {
}
然后在控制器中我们有:
@Controller
@Component
@RequestMapping("/somepath")
public class MyController {
@Autowired
private MyService service;
...
@MyAnnotation
@RequestMapping(value = "/myendpoint", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Object myEndpoint(@RequestBody MyRequestObject requestObject, HttpServletRequest request, HttpServletResponse response) {
...
return service.doSomething(requestObject);
}
}
然后我们有一个如下所示的单元测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"../path/to/applicationContext.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class MyControllerTest {
private MockMvc mockMvc;
@InjectMocks
private MyController controller;
@Mock
private MyService myService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).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());
}
}
测试运行良好,但围绕注释 (MyAnnotation) 定义的方面没有执行。当端点由真实请求触发时(例如在 servlet 容器中运行时),这执行得很好,但在测试中运行时不会触发。
这是 MockMvc 的一个特殊“功能”,它不会触发方面吗?
仅供参考,我们的 applicationContext.xml 配置为:
<aop:aspectj-autoproxy/>
正如我提到的,这些方面在现实中确实有效,只是在测试中没有。
有谁知道如何让这些方面着火?
谢谢!