如何在SpringBootTest中排除Aspectj?

时间:2018-04-03 02:12:07

标签: java spring-boot junit

我是春季靴子测试的新手。这是我的情况:   我想运行spring boot test但是排除了一些组件,比如组件包含@Aspect annotation。因为在我的测试用例中,一些代码将被aspect组件切入并导致NullPointException。

我尝试使用像这样的@SpringBootTest参数类 @SpringBootTest(classes = TestApplication.class)和TestApplication.class是一个springboot主类,带有@ComponentScan注释,用于扫描组件排除@Aspect类。我认为这不是解决这个问题的明确方法,它对我不起作用,有人可以帮帮我吗?

1.测试案例:请查看评论标志1.这是一个查询数据库操作

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CheckCardFormatTest{
   @Autowired
   private XxxServiceImpl xxxService; // service layer 
   ....
   @Test
    public void testMainCardFormat() {
        String result=xxxService.query("someParam");// 1.
         ....
    }
   ....
}

2.有问题请看注释2,getRequest()方法会导致NullPointException.Because我的方面类会中断查询 - 数据库操作

@Aspect
@Component
public class AbcAspect {
  @Around(value = "execution(*com.xx.preparedStatement_execute(..))")
  public Object druidIntercept(ProceedingJoinPoint pjp) throws Throwable {
  ....
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
    HttpServletRequest request = servletRequestAttributes.getRequest();// 2.
  ....
}

1 个答案:

答案 0 :(得分:0)

将@TestComponent添加到AbcsAspect类 这是@TestComponent的javadoc

  

/ **    * {@link Component @Component}可以在bean仅用于测试时使用,    *并且应该从Spring Boot的组件扫描中排除。    *

   *请注意,如果您直接使用{@link ComponentScan @ComponentScan}而不是依赖    *在{@code @SpringBootApplication}上你应该确保{@link TypeExcludeFilter}是    *声明为{@link ComponentScan#excludeFilters()excludeFilter}。    *    * @author Phillip Webb    * @since 1.4.0    * @see TypeExcludeFilter    * @see TestConfiguration    * /