samedi 10 septembre 2016

How do I mock a private static final variable(that's initialized via a private constructor) using Powermock and Mockito?

Here's my source class -

public class ClassToTest extends AbstractSuperClass<Integer>{
 private static final ClassToTest INSTANCE = new ClassToTest(); // line 2 need to mock this variable

 static ClassToTest get(){
    return INSTANCE;
 }
 private ClassToTest(){
  super(Integer.class);// line 2
}

Here's my attempt so far at testing it

 @RunWith(PowerMockRunner.class)
 @PrepareForTest(ClassToTest.class)
 public class TestClass {
     private ClassToTest testClass;@
     Before
     public void setUp() {
         // each of the below attempts fails at line 1  because of the call to line 2 (annotated above).
         // Attempt A.  
         testClass = WhiteBox.newInstance(ClassToTest.class);
         //Attempt B.
         testClass = mock(ClassToTest.class);
         WhiteBox.setInternalState(ClassToTest.class, "INSTANCE", testClass);
     }
     @Test
     public void dummy() {
         // irrelevant
     }
 }

I'm trying to effectively mock out ClassToTest.INSTANCE and the call to its private constructor. How would I do that?

Aucun commentaire:

Enregistrer un commentaire