在Spring测试中没有调用Aspect

时间:2015-06-08 21:59:40

标签: java spring spring-aop spring-test spring-aspects

我正在使用Spring 4.16并且我有ValidationAspect,它验证方法参数并抛出ValidationException如果有问题。这是在我运行服务器并发送请求时调用,但不是在测试时调用:

package com.example.movies.domain.aspect;
...
@Aspect
public class ValidationAspect {

    private final Validator validator;

    public ValidationAspect(final Validator validator) {
        this.validator = validator;
    }

    @Pointcut("execution(* com.example.movies.domain.feature..*.*(..))")
    private void selectAllFeatureMethods() {
    }

    @Pointcut("bean(*Service)")
    private void selectAllServiceBeanMethods() {
    }

    @Before("selectAllFeatureMethods() && selectAllServiceBeanMethods()")
    public synchronized void validate(JoinPoint joinPoint) {
         // Validates method arguments which are annotated with @Valid
    }
}

配置文件,我创建方面bean的方面

package com.example.movies.domain.config;
...
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AspectsConfiguration {

    @Bean
    @Description("Hibernate validator. Used to validate request's input")
    public Validator validator() {
        ValidatorFactory validationFactory = Validation.buildDefaultValidatorFactory();
        return validationFactory.getValidator();
    }

    @Bean
    @Description("Method validation aspect")
    public ValidationAspect validationAspect() {
        return new ValidationAspect(this.validator());
    }
}

所以这是测试,它应该在它进入addSoftware方法之前抛出ValidationException,因为它是一个无效的softwareObject。

@ContextConfiguration
@ComponentScan(basePackages = {"com.example.movies.domain"})
public class SoftwareServiceTests {
    private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareServiceTests.class.getName());

    private SoftwareService softwareService;
    @Mock
    private SoftwareDAO dao;
    @Mock
    private MapperFacade mapper;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        this.softwareService = new SoftwareServiceImpl(this.dao);
        ((SoftwareServiceImpl) this.softwareService).setMapper(this.mapper);

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SoftwareServiceTests.class);
        ctx.getBeanFactory().registerSingleton("mockedSoftwareService", this.softwareService);
        this.softwareService = (SoftwareService) ctx.getBean("mockedSoftwareService");

    }

    @Test(expected = ValidationException.class)
    public void testAddInvalidSoftware() throws ValidationException {
        LOGGER.info("Testing add invalid software");
        SoftwareObject softwareObject = new SoftwareObject();
        softwareObject.setName(null);
        softwareObject.setType(null);

        this.softwareService.addSoftware(softwareObject); // Is getting inside the method without beeing validated so doesn't throws ValidationException and test fails
    }
}

如果我运行该服务并从post请求中添加此无效用户,则会抛出ValidationException。但由于某种原因,它永远不会从测试层执行ValidationAspect方法

我的服务

package com.example.movies.domain.feature.software.service;
...
@Service("softwareService")
public class SoftwareServiceImpl
    implements SoftwareService {

    @Override
    public SoftwareObject addSoftware(@Valid SoftwareObject software) {
         // If gets into this method then software has to be valid (has been validated by ValidationAspect since is annotated with @Valid)
         // ...
    }
}

我不明白为什么没有调用aspect,因为mockedSoftwareService bean位于feature包中,bean名称以" Service"结尾,所以它满足两个条件。你对可能发生的事情有任何想法吗?提前致谢

修改

@Service("softwareService")
public class SoftwareServiceImpl
    implements SoftwareService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareServiceImpl.class.getName());

    private SoftwareDAO dao;
    private MapperFacade mapper;

    @Autowired
    private SoftwareCriteriaSupport criteriaSupport;

    @Autowired
    private SoftwareDefaultValuesLoader defaultValuesLoader;

    @Autowired
    public SoftwareServiceImpl(SoftwareDAO dao) {
        this.dao = dao;
    }

    @Autowired
    @Qualifier("domainMapper")
    public void setMapper(MapperFacade mapper) {
        this.mapper = mapper;
    }

   // other methods

}

4 个答案:

答案 0 :(得分:5)

不确定你要做什么,但你的@ContextConfiguration没用,因为你没有使用Spring Test来运行你的测试(这需要一个@RunWith或一个超类来自Spring Test)。

接下来,您将添加一个已经完全模拟和配置的单例(这是上下文假设的)。我强烈建议使用Spring而不是解决它。

首先在测试类中创建一个配置进行测试,这个配置应该扫描并注册模拟的bean。第二次使用Spring Test来运行测试。

@ContextConfiguration
public class SoftwareServiceTests extends AbstractJUnit4SpringContextTests {
    private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareServiceTests.class.getName());

    @Autowired
    private SoftwareService softwareService;

    @Test(expected = ValidationException.class)
    public void testAddInvalidSoftware() throws ValidationException {
        LOGGER.info("Testing add invalid software");
        SoftwareObject softwareObject = new SoftwareObject();
        softwareObject.setName(null);
        softwareObject.setType(null);

        this.softwareService.addSoftware(softwareObject);
    }

    @Configuration
    @Import(AspectsConfiguration.class)
    public static class TestConfiguration {

        @Bean
        public SoftwareDAO softwareDao() {
            return Mockito.mock(SoftwareDAO.class);
        }

        @Bean
        public MapperFacade domainMapper() {
            return Mockito.mock(MapperFacade.class)
        }

        @Bean
        public SoftwareService softwareService() {
            SoftwareServiceImpl service = new SoftwareServiceImpl(softwareDao())
            return service;
        }

    }
}

答案 1 :(得分:1)

很好理解Spring AOP的工作原理。如果Spring托管bean符合任何方面的条件(每个方面一个代理),则会将其包装在代理(或少数)中。

通常,Spring使用接口来创建代理,尽管它可以使用像cglib这样的库来处理常规类。如果您的服务意味着Spring创建的实现实例包含在处理方法验证的方面调用的代理中。

现在,您的测试手动创建了SoftwareServiceImpl实例,因此它不是Spring托管bean,因此Spring无法将其包装在代理中以便能够使用您创建的方面。

您应该使用Spring来管理bean以使方面有效。

答案 2 :(得分:0)

确实有两件事要实现:

1)对象树的根必须由应用程序上下文中注册的扫描对象来解析。如果您使用new(),则无法解析AOP注释。

2)需要注册Annotations和AOP方面类。

ad 1)@Autowire您的根对象将解决问题

ad 2)确保@Component使用正确的过滤器:    @Component()或@Component(“您的完整名称空间包过滤器”)

检查:

echo "1" > file | ( read; echo "2" > file)

答案 3 :(得分:0)

您需要使用 srping 运行:

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

}