如何让Aspect在Spring中进行Junit测试?

时间:2014-08-05 14:26:33

标签: spring junit aop

我的观点:

@Aspect
public class testAutomationAspect {
    @Before(value="execution(* my.package.*.*(..))")
    public void BeforeTest(){

        System.out.println("?????");
    }
}

我的测试:

@ContextConfiguration(locations={"classpath:context/automation-context.xml"})
public class TestNgExample extends TestCase{

    public void testSomething2() throws java.io.IOException{

        Assert.assertNotNull(null);
    }

}

我的XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">


    <aop:aspectj-autoproxy  proxy-target-class="true">

        <aop:include name="automationAspect" />
    </aop:aspectj-autoproxy>

    <bean id="automationAspect" class="my.package.AutomationAspect" />

</beans>

现在,当junit运行时,方面不会运行。我的猜测是xml上下文没有定义测试用例,所以它们在某种程度上处于不同的上下文中。你将如何在相同的背景下获得junit测试?我尝试使用@ContextConfiguration来实现这一点。不确定这是否是正确的方法。

3 个答案:

答案 0 :(得分:2)

Spring AOP是基于代理的,仅适用于Spring Beans。除非您的测试类是Spring bean,否则它将无效。为了将方面应用于普通(非Spring Bean)POJO,您可以使用完整的AspectJ,它可以在没有代理的情况下工作。

答案 1 :(得分:1)

无论如何,你的问题是类TestNgExample不是Spring上下文的一部分。将每个方法包装在一个类中,并将其声明为bean。

答案 2 :(得分:0)

您必须使用SpringJUnit4ClassRunner运行测试,然后您的所有方面,验证器和其他方法都可以工作:) @ContextConfiguration没问题。您需要它来定义测试上下文。

@RunWith(SpringJUnit4ClassRunner.class)

但是我不确定如果你将它们附加到测试中,Aspects会起作用。也许最好在你要测试的服务方法周围调用它们。