Mocking getClass ()

In Java, I want to write a test for a 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);
    }
}

Problem with the next 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));
   }
}

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

Foo$$EnhancerByMockitoWithCGLIB$$45508b12

For this reason, the test failed because SOME_SET.contains (clazz) returns false.

I was not able to make fun of the getClass () method in Foo:

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

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

The question is how to get the wearClass's getClass () method to return the same value as the getClass ()'s method for a real (not mocking) object ?

+4
4

Mockito.mock(Foo.class) Foo, Foo. , , Foo. , .

isValid , ( , isAssignableFrom) . , .

, , - , (, isValid (object))? - , clazz . :

    public boolean isValid(Object obj) {
        return SOME_SET.stream().anyMatch(clazz -> clazz.isInstance(obj));
    }
+3

Foo . Foo.class param. MyClass.isValid, - Foo.

+2

: .

: mocked . , , . : - , .

-:

@Test
public void testIsValidForInvalidClass() {
  assertThat(target.isValid(String.class), is(false));
}

@Test
public void testIsValidForValidClass() {
  assertThat(target.isValid(Foo.class), is(true));
}

. -, . Class!

+1

When initializing the 'foo' object, simply create an object of type Foo instead of creating a layout of Foo. For example, if possible:

Foo foo = new Foo()
0
source

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


All Articles