单元测试中未触发Spring Aspect

时间:2013-10-30 18:22:34

标签: unit-testing spring-mvc aop

好的,我们正在谈论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/>

正如我所提到的,这些方面确实在现实中起作用,而不是在测试中。

任何人都知道如何解决这些问题?

谢谢!

3 个答案:

答案 0 :(得分:5)

好的..所以解决方案最终出现了......你猜对了..阅​​读文档:/

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 {
...

答案 1 :(得分:0)

我使用 MockMVC 进行了类似的设置,以通过层执行集成测试。注释在没有任何额外代码的情况下工作正常,直到我重命名注释的包。它停止工作。注释不会执行。敲了一会儿,我发现我已经解决了一次:ComponentScan annotation's package。

您的应用程序的配置类文件中可能有类似的语句。您将需要在您的测试类中重复任何这些类型的声明。

@SpringBootTest
@AutoConfigureMockMvc
@ComponentScan("annotation.package")
public class MyControllerTest {

}

答案 2 :(得分:0)

你需要在测试中启用aop:

@EnableAspectJAutoProxy
@RunWith(SpringJUnit4ClassRunner.class)
public class MyControllerTest {

}