在Java中使用AspectJ进行单元测试

时间:2014-08-29 11:58:48

标签: java unit-testing aspectj-maven-plugin

我正在开发一个使用AspectJ和Java的应用程序。在开发中,我一起使用ajc和java。 AspectJ在必要时调用一些代码段,我想测试AspectJ调用的这些代码段。我尝试用Mockito做但我失败了,有没有人知道其他任何方法来测试它?

2 个答案:

答案 0 :(得分:2)

我不确定如何在纯 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依赖是:

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
</dependency>

答案 1 :(得分:2)

我刚刚创建了一个JUnit4 Runner,允许在JUnit测试用例上进行AspectJ加载时编织。这是一个简单的例子:

我创建了一个HelloService来返回问候语。我创建了一个Aspect来在问候大写中创建名称。最后,我创建了一个单元测试,以使用具有小写名称的HelloService,并期望得到一个大写结果。

该示例的所有细节都是GitHub项目的一部分,以供参考: https://github.com/david-888/aspectj-junit-runner

只需在类路径中包含最新的aspectj-junit-runner JAR即可。那么你的测试可能如下所示:

@AspectJConfig(classpathAdditions = "src/test/hello-resources")
@RunWith(AspectJUnit4Runner.class)
public class HelloTest {

    @Test
    public void getLiveGreeting() {
        String expected = "Hello FRIEND!";
        HelloService helloService = new HelloService();
        String greeting = helloService.sayHello("friend");
        Assert.assertEquals(expected, greeting);
    }

}