Mocking getClass()

Viewed 9627

In Java I want to write test for method (simplified snippet):

public class MyClass {
    private static final Set<Class> SOME_SET = new HashSet<Class>(Arrays.asList(Foo.class, Bar.class));

    public boolean isValid(Class clazz){
        return SOME_SET.contains(clazz);
    }
}

The problem with following test

import static org.mockito.Mockito.when;
import org.mockito.Mockito;

public class MyClassTest {
    @Test
    public void isValid_Foo_returnsTrue(){
        Foo foo = Mockito.mock(Foo.class);
        MyClass target = new MyClass();
        assertTrue(target.isValid(foo));
   }
}

is that on mocked class Foo, foo.getClass() returns the class name with additional suffix. Something like this:

Foo$$EnhancerByMockitoWithCGLIB$$45508b12

Because of this reason test fails because SOME_SET.contains(clazz) returns false.

I was unable to mock getClass() method on Foo:

Mockito.when(foo.getClass()).thenReturn(Foo.class);

Because compiler was complaining: The method thenReturn(Class<capture#1-of ? extends Foo>) in the type OngoingStubbing<Class<capture#1-of ? extends Foo>> is not applicable for the arguments (Class<Foo>)

The question is, how to achieve that getClass() method of mocked object returns same value as getClass() method on real(non mocked) object?

5 Answers

This is possible with a, currently incubating, alternative mock maker implementation. See here how to enable it. Calling getClass on such mocks returns the original class so equals will work as expected.

Related