Susitha Ravinda Senarath
Susitha Ravinda Senarath

Reputation: 1678

Mock private static final variables in the testing class

I have a few private static final fields in the class I want to test. Like follows

public class ClassToTest{
    ....
    private static final Myclass myclass = MyClassFactory.getMyClass(type.firstType);
    ....
}

The type is a enum in the MyClassFactory. That factory do is it initialize object according to type passed and return.

My question is does powermock support this and if so how to do this.

Upvotes: 2

Views: 12316

Answers (3)

Tom Jonckheere
Tom Jonckheere

Reputation: 1648

Why do you want to test this value? Shouldn't you test your enum, test if it returns the correct value when a given type is passed to it. If you want to test the assignment of the enum to the field you are doubting basic java assignment.

Upvotes: 1

RamonBoza
RamonBoza

Reputation: 9038

You can use reflection also if any mock library works for you.

Field f = classToTest.getclass().getDeclaredField("myclass ");
f.setAccessible(true);
f.set(classToTest,/*NEW VALUE*/);

Upvotes: 4

DaveH
DaveH

Reputation: 7335

PowerMock ( + a mocking framework ) will allow you to do this. Presumeably you're talking about mocking MyClassFactory.getMyClass() ?

See this question for an example

Upvotes: 2

Related Questions