我正在使用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
}
}
如果我运行该服务,并从发帖请求中添加了这个无效的用户,则会抛出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)
// ...
}
}
我不明白为什么不调用方面,因为mockedSoftwareService Bean位于功能部件包中,并且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
}
[不确定您要做什么,但您的@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;
}
}
}
理解Spring AOP的工作原理很好。如果一个Spring托管bean有资格使用任何方面(每个方面一个代理),则将其包装在一个(或几个)代理中。
通常,Spring可以使用该接口创建代理,尽管它可以使用cglib之类的常规类来处理代理。对于您的服务,这意味着Spring创建的实现实例被包装在代理中,该代理处理用于方法验证的方面调用。
现在,您的测试将手动创建SoftwareServiceImpl实例,因此它不是Spring托管的bean,因此Spring没有机会将其包装在代理中以能够使用您创建的方面。
您应该使用Spring来管理Bean以使方面正常工作。
确实有两件重要的事情要实现:
1)对象树的根必须由应用程序上下文中注册的扫描对象来解析。如果使用new(),则无法解析AOP注释。
2)注释和AOP方面类需要注册。
广告1)@Autowire您的根对象将完成任务
ad 2)确保@Component使用正确的过滤器:@Component()或@Component(“您的完整名称空间包过滤器”)
检查:
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx)
{
return args ->
{
log.debug("Let's inspect the beans provided by Spring Boot:");
List<String> beanNames = Arrays.asList(ctx.getBeanDefinitionNames());
Assert.isTrue( beanNames.contains("yourAspectClassName"));
};
}