Why does Mockito skip the initialization of the member variable of my abstract class
abstract-class, java, mockito, unit-testing
Solution
This is the expected behavior, when you mock something the created instance is a complete mock, so it makes no sense to initialize the fields as behavior is defaulted.
Aside of that, fields can be initialized by a constructor in concrete or abstract classes, as mocks instantiation bypasses the constructor simply because it's a mock, it is even more irrational to initialize them.
Trying to call the real method is usually wrong when using mocks. Instead one should stub the behavior of the mock.
Mockito.when(foo.isNull(Mockito.anyObject())).thenReturn(false);
Assert.assertFalse(foo.isNull("baaba")); // assertion always passing
I don't know your actual use case but maybe you want a partial mock, with a `spy`. Though that's still considered bad practice as it usually means you need to refactor the code to use composition.
Problem
I'm trying to test an abstract class and Mockito does not initialize my member variables. Here's a simple example to show you my problem. This is an abstract class that initializes its 'field' member: ``` import java.util.ArrayList; import java.util.Collection; public abstract class Foo { private final Collection field = new ArrayList(); protected Foo() { System.out.println("In constructor"); } public boolean isNull(Object o) { field.add(o); return o == null; } abstract void someAbstractMethod(); } ``` Here the test class: ``` import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class FooTest { @Test public void testSomething() { final Foo foo = Mockito.mock(Foo.class); Mockito.when(foo.isNull(Mockito.anyObject())).thenCallRealMethod(); Assert.assertFalse(foo.isNull("baaba")); } } ``` When the test is run it throws a NPE because the variable 'field' is not initialized! What am I doing wrong?