我不确定如何在普通Java和JUnit中执行此操作,但是如果您可以访问Spring-Integration-Test,则可以轻松使用MockMVC及其提供的支持类.
在下面,您可以看到一个示例,在该示例中,我正在测试一个控制器,其中包含一个Aspect:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class ControllerWithAspectTest {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockMvc mockMvc;
@Autowired
@InjectMocks
private MongoController mongoController;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
// if you want to inject mocks into your controller
MockitoAnnotations.initMocks(this);
}
@Test
public void testControllerWithAspect() throws Exception {
MvcResult result = mockMvc
.perform(
MockMvcRequestBuilders.get("/my/get/url")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
}
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
static class Config extends WebMvcConfigurerAdapter {
@Bean
public MongoAuditingAspect getAuditingAspect() {
return new MongoAuditingAspect();
}
}
}
即使您没有在应用程序中配置Spring,也可以使用上面的方法,因为我使用的方法将允许您有一个配置类(可以并且应该是驻留在其自己文件中的公共类).
而且,如果@Configuration类使用@EnableAspectJAutoProxy(proxyTargetClass = true)进行注释,则Spring将知道它需要启用测试/应用程序中的各个方面.
如果您需要任何其他说明,我将对其进行进一步的编辑.
编辑:
Maven Spring-Test依赖项是:
org.springframework
spring-test
${spring.version}
test