繁体   English   中英

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

[英]Unit testing with AspectJ in Java

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

我不确定如何在普通JavaJUnit中执行此操作 ,但是如果您可以访问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 ,也可以使用上述方法,因为我使用的方法将允许您拥有配置类(可以且应该是驻留在其自己的文件中的公共类)。

如果使用@EnableAspectJAutoProxy(proxyTargetClass = true)注释@Configuration类, Spring将知道它需要在您的测试/应用程序中启用方面。

如果您需要任何额外的说明,我会提供进一步的编辑。

编辑:

Maven Spring-Test依赖是:

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

我刚刚创建了一个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);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM