3

我正在开发一个将 AspectJ 与 Java 结合使用的应用程序。在开发中,我将ajc和java一起使用。AspectJ 在必要时会调用一些代码段,我想测试 AspectJ 调用的这些代码段。我试图用 Mockito 来做,但我失败了,有谁知道其他方法来测试它吗?

4

2 回答 2

2

我不确定如何在纯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,您也可以使用上述方法,因为我使用的方法将允许您拥有一个配置类(可以并且应该是驻留在它自己的文件中的公共类)。

如果@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>
于 2014-08-29T12:36:59.733 回答
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);
    }

}
于 2016-12-11T11:51:41.080 回答