使用springBootTest进行单元测试,单元测试代码如下, @SpringBootTest 注解会扫描全部组件,其中包括@Aspect注解的组件,注释//1 处是一个service并执行数据库操作
@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代码,会拦截所有数据库操作。注释 //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.
....
}
已找到排除某个component的解决方案:在类名上加注解@TestComponent ,单元测试会过滤掉该类 不扫描。