jeudi 22 octobre 2015

How do I set a private static final field in a class with private constructor using PowerMockito?

I'm trying to set a private static final field in a class with private constructor for a JUnit test. When I boil the code down to its basics, I get the following:

public class Foo {
    private static final boolean FLAG = false;
    private Foo() { /* don't call me */  }
    public static boolean get() { return FLAG; }
}

My tests looks like this:

@RunWith(PowerMockRunner.class)
@PrepareEverythingForTest  // Whitebox fails without this line
public class FooTest {
    @Test
    public void testGet() {
        Whitebox.setInternalState(Foo.class, "FLAG", true);
        assertTrue(Foo.get());
    }
}

And here is an excerpt from my POM file:

<junit.version>4.11</junit.version>
<powermock.version>1.5.4</powermock.version>
<mockito.version>1.9.5</mockito.version>

When I put a breakpoint on return FLAG;, I can clearly see that FLAG was set to true in IntelliJ's debugger. Yet the test fails with an AssertionError.

Any ideas what to do to make this work?





Aucun commentaire:

Enregistrer un commentaire