jeudi 10 septembre 2015

How do I mock a class with private fields?

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 getName(){ 
        String name = ExternalCall(id); // need field id here
        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, "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?

Aucun commentaire:

Enregistrer un commentaire