简体   繁体   中英

Mock Abstract Class in EasyMock

I am using EasyMock 2.4 and can't upgrade to latest version due to dependencies. I need to mock abstract class but not able to do it with createMock method. It throws an error that class is not an interface.

Can anyone help me in solving this problem?

There is an abstract class called ClassA (I can't modify this class):

public abstract class ClassA {

}

There is another MyTest class which mocks ClassA:

public class MyTest {
    private ClassA mockClassA;

    @Before
    public void setup() {
        mockClassA = createMock(ClassA.class); //Line number: 28
    }
}

while running this it throws below exception at createMock call:

java.lang.IllegalArgumentException: ClassA is not an interface

at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:590)
at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:557)
at java.lang.reflect.WeakCache$Factory.get(WeakCache.java:230)
at java.lang.reflect.WeakCache.get(WeakCache.java:127)
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:419)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:719)
at org.easymock.internal.JavaProxyFactory.createProxy(JavaProxyFactory.java:13)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:40)
at org.easymock.EasyMock.createMock(EasyMock.java:60)
at mypackage.MyTest.setup(MyTest.java:28)

EasyMock prior to v3.0 was using Java proxies mechanism to create mocks. This mechanism is capable only of creating proxies for interfaces, so there is no way you can mock a class (abstract class) with easy mock without upgrading to v3.0 at least.

You have the following options:

  1. Upgrade EasyMock to v3.0+ (what prevents your from?)
  2. Use other mocking library in parallel with EasyMock (eg Mockito)
  3. Create your own subclass of ClassA in test and override methods there for testing. But this one is clearly a workaround that may not provide you with enough flexibility.

Actually what do you expect from your mock? (Eg to stub some method calls, or to do some method call verifications, other...)

EasyMock Class extension worked to create mock object for class or interface. I used import static org.easymock.classextension.EasyMock.* ; instead of import static org.easymock.EasyMock.* ;

Yes. Prior to EasyMock 3, you need the class extension to mock classes. However, latest EasyMock versions have not much dependencies (only Objenesis in fact).

Which one is blocking you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM