鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ Springboot單元測試如何排除Aspect

Springboot單元測試如何排除Aspect

使用springBootTest進行單元測試,單元測試代碼如下, @SpringBootTest 注解會掃描全部組件,其中包括@Aspect注解的組件,注釋//1 處是一個service并執(zhí)行數(shù)據(jù)庫操作

@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.
         ....
    }
   ....
}

如下是aop代碼,會攔截所有數(shù)據(jù)庫操作。注釋 //2那里是要獲取HttpServletRequest,如果在正常的HTTP請求中運行正常。 但是在單元測試中會獲取不到 報空指針異常,所以我想要@SpringbootTest注解掃描排除掉aop,該如何去解決呢?

@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.
  ....
}
回答
編輯回答
好難瘦

@Profile你值得擁有

2017年6月26日 14:16
編輯回答
純妹

已找到排除某個component的解決方案:在類名上加注解@TestComponent ,單元測試會過濾掉該類 不掃描。

2017年11月21日 05:30