您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Transactional annotation avoids services being mocked

Transactional annotation avoids services being mocked

发生的事情是你的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...(即,在运行时隐藏在代理后面)也应该可以正常工作

其他 2022/1/1 18:16:04 有493人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶