Search code examples
junitfieldprivate

Junit private fields


Here is an existing class and its method I am trying to mock:

public class ClassUndertest{

   private Object field_private = new Object();

   public Object method_public()
   {
       field_private.method();
       method_private();
   }


   private Object method_private()
   {
       ....
       return Object;
   }

}

My tests partially mocks ClassUndertest:

   ClassUndertest partialmockinstance = PowerMock.createPartialMock(ClassUndertest.class, "method_private");

When I run mock object:

 partialmockinstance.method_public();

field_private is not intialized and so test throws null pointer.

Is there anyway to circumvent this issue?


Solution

  • Fields are initialized when a constructor is invoked. I think the default behaviour of PowerMock is to not invoke any constructor.

    With looking at the javadoc I would try the following method instead:

    ClassUndertest partialmockinstance = PowerMock.createPartialMockAndInvokeDefaultConstructor(ClassUndertest.class, "method_private");