Using Spring to insert EasyMock mocks raises a ClassCastException

I am trying to get Spring to embed EasyMock mocks in my unit tests.

In my applicationContext.xml, I have this:

<bean id="mockService"  class="org.easymock.EasyMock" factory-method="createMock"  name="MockService">
    <constructor-arg index="0" value="my.project.Service"/>
</bean>

In my unit test, I have this:

@Autowired
@Qualifier("mockService")
private Service service;

public void testGetFoo() {
    Foo foo = new Foo();

    expect(service.findFoo()).andReturn(foo);
    replay(service); // <-- This is line 45, which causes the exception

    // Assertions go here...
}

When I try to run my test, I get this stack trace:

java.lang.ClassCastException: org.springframework.aop.framework.JdkDynamicAopProxy
at org.easymock.EasyMock.getControl(EasyMock.java:1330)
at org.easymock.EasyMock.replay(EasyMock.java:1279)
at TestFooBar.testGetFoo(TestVodServiceLocator.java:45)

I am completely new to both Spring and EasyMock, but it seems to me that the error is caused by the fact that EasyMock tries to call the method on what, in its opinion, is an instance of EasyMock, but in fact is a dynamic proxy created by Spring. As I understand it, dynamic proxies implement only the methods defined in the interface, in this case, the interface for the Service.

, , ( ), , , -, .

, : ?

+3
4

!

ApplicationContext.xml:

<bean id="txProxyAutoCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <list>

            <value>*Service</value>
            <!--   ^^^^^^^^    
               This is the problem!
            -->
        </list>
    </property>
    <property name="interceptorNames">
        <list>
            <value>txAdvisor</value>
        </list>
    </property>
</bean>

..., Spring - beans , "".

beans wild card. , , - , * beans FooService, .

+4

- EasyMock - Spring :

public static <T> T unwrap(T proxiedInstance) {
  if (proxiedInstance instanceof Advised) {
    return unwrap((T) ((Advised) proxiedInstance).getTargetSource().getTarget());
  }

  return proxiedInstance;
}

, -, .

+6

- . Spring, EasyMock. , factory, , Spring.

, , bean . , . . 3 java 3 XML ( 1 reset ) ? Service service = (Service) createMock (Service.class). , , , , , . reset , , , .

, , , , .

+1

, , , .

, Spring . , , :

public static <T> T createMock(final Class<T> toMock) {
    return createControl().createMock(toMock);
}

Spring , T ( , , ), , java.lang.Object. , my.project.Service .

, Spring .

+1

Source: https://habr.com/ru/post/1709289/


All Articles