发生的事情是你的ValidationService被包装在JdkDynamicAopProxy中,因此,当Mockito将模拟程序注入到服务中时,它看不到任何将其注入的字段。你需要执行以下两项操作之一:
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
ValidationService validationService = (ValidationService) unwrapProxy(level2ValidationService);
ReflectionTestUtils.setField(validationService, "countryService", countryService);
}
public static final Object unwrapProxy(Object bean) throws Exception {
/*
* If the given object is a proxy, set the return value as the object
* being proxied, otherwise return the given object.
*/
if (AopUtils.isAopProxy(bean) && bean instanceof Advised) {
Advised advised = (Advised) bean;
bean = advised.getTargetSource().getTarget();
}
return bean;
}
请注意,从Spring 4.3.1开始,ReflectionTestUtils应该自动打开代理。所以
ReflectionTestUtils.setField(validationService, "countryService", countryService);
现在,即使你countryService
使用@Transactional
,@Cacheable...
(即,在运行时隐藏在代理后面)也应该可以正常工作