I'm trying to test a singleton class with mockito, something like this:
public class Single {
private String id;
private Single(){} //private constructor
public static Single getSingle(){ // ***code to get instance*** }
// method I want to test
public String getId(){ return id; }
}
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, "123");
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?
Thanks.
Aucun commentaire:
Enregistrer un commentaire