java - How do I set a primitive private static final field in a class with private constructor using PowerMockito? -
i'm trying set private static final
field in class private
constructor junit test. when boil code down basics, 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 this:
@runwith(powermockrunner.class) @prepareeverythingfortest // whitebox fails without line public class footest { @test public void testget() { whitebox.setinternalstate(foo.class, "flag", true); asserttrue(foo.get()); } }
and here excerpt pom file:
<junit.version>4.11</junit.version> <powermock.version>1.5.4</powermock.version> <mockito.version>1.9.5</mockito.version>
when put breakpoint on return flag;
, can see flag
set true
in intellij's debugger. yet test fails assertionerror
.
any ideas make work?
update: using reflection doesn't seem work, either:
@test public void testget_usingreflection() throws exception { setfield(whitebox.invokeconstructor(foo.class), "flag", true); asserttrue(foo.get()); } public static void setfield(object targetobject, string fieldname, object value) throws nosuchfieldexception, illegalaccessexception { class clazz = targetobject.getclass(); field field = clazz.getdeclaredfield(fieldname); field.setaccessible(true); field modifiers = field.class.getdeclaredfield("modifiers"); modifiers.setaccessible(true); modifiers.setint(field, field.getmodifiers() & ~modifier.final); field.set(targetobject, value); }
the setfield()
method 1 have available through internal library. unfortunately, produces same result: assertionerror
update 2: getting rid of powermock doesn't much, either, apparently:
@test public void testget_usingreflectionwithoutpowermock() throws exception { setfield(foo.class.getdeclaredfield("flag"), true); asserttrue(foo.get()); } public static void setfield(field field, object value) throws nosuchfieldexception, illegalaccessexception { field.setaccessible(true); field modifiers = field.class.getdeclaredfield("modifiers"); modifiers.setaccessible(true); modifiers.setint(field, field.getmodifiers() & ~modifier.final); field.set(null, value); }
for this, removed powermock annotations class level...
i've posted question powermock mailing list now.
i had similar thing test, difference static final variable object
rather primitive type. , indeed changing boolean
boolean
makes work.
public class foo { private static final boolean flag = false; private foo() { /* don't call me */ } public static boolean get() { return flag; } }
also recommend using @preparefortest(someclass.class)
someclass
has static final field rather @prepareeverythingfortest
because if it's big project may take time prepare everything.
Comments
Post a Comment