I'm trying to test a singleton class with Mockito, something like this:
public class Single {
private ID id;
private Single(){} //private constructor
public static Single getSingle(){ // ***code to get instance*** }
// method I want to test
public String getName(){
String name = id.getRawName(); // need field id here
** additional operations on name ** // code need to be tested
return name;
}
}
I tried to mock this class and set field "id" with reflection, like this:
Single sg = Mockito.mock(Sincle.class);
Field myID = sg.getClass().getDeclaredField("id"); // fails here
myID.setAccessible(true);
myID.set(sg, <ID instance>);
However it fails at getDeclaredField()
method, with exception
java.lang.NoSuchFieldException: id
I guess it's because id
field is null
in instance sg.
So I'm wondering if there's anything I can do to test this method without modify the original class?