dimanche 15 mai 2016

Mock private static final String using Mockito

I am having a difficulty time mocking a private static final String field in a class. Here is my java sample code:

public class Fruit {
private static final String FRUIT = "apple";

public void getFruit() {
    System.out.println("I like " + FRUIT);
}

}

And I used Mockito to mock the FRUIT variable so that I can change the value of FRUIT from "apple" to "mango". For that here is my test:

public class FruitTest {
@Test
public void testFruit() throws NoSuchFieldException, SecurityException, Exception {
    setFinalStatic(Fruit.class.getDeclaredField("FRUIT"), "mango");
    Fruit fruit = new Fruit();
    fruit.getFruit();
}

static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}

}

I was expecting when I do System.out.println("I like " + FRUIT); it will print mango, but still it is printing apple. I would really appreciate if anyone can help me with this ONLY USING MOCKITO and not PowerMock etc.

Aucun commentaire:

Enregistrer un commentaire