Spring Bean Injection Failing Due To Proxy

后端 未结 1 804
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 23:13

Spring Version: 3.2.4.RELEASE and 3.2.9.RELEASE

Mockito Version: 1.8.5

I\'ve been trying to introduce H2 tests to an old pr

1条回答
  •  有刺的猬
    2021-01-15 23:43

    Alright, once I realised that the class was being proxied due to the @Transactional annotation, the solution to the problem became clearer. What I needed to do was unwrap the proxy, and set the mocked object directly on that:

    So in my AbstractIntegrationTest:

    /**
     * Checks if the given object is a proxy, and unwraps it if it is.
     *
     * @param bean The object to check
     * @return The unwrapped object that was proxied, else the object
     * @throws Exception
     */
    public final Object unwrapProxy(Object bean) throws Exception {
        if (AopUtils.isAopProxy(bean) && bean instanceof Advised) {
            Advised advised = (Advised) bean;
            bean = advised.getTargetSource().getTarget();
        }
        return bean;
    }
    

    Then in my @Before:

    @Mock
    private ProcessHelper processHelper;
    
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    
        IXMLBatchProcessor iXMLBatchProcessor = (IXMLBatchProcessor) unwrapProxy(xmlProcessor);
        ReflectionTestUtils.setField(iXMLBatchProcessor , "processHelper", processHelper);
    }
    

    This left all the @Autowired classes intact, while injecting the correct mocked object.

    0 讨论(0)
提交回复
热议问题