lundi 22 mai 2017

Unit tests with Mockito, spy and reflection on a Map object

I have a slightly complicated situation, and not sure how to handle it. There is an object with a private variable map (the object has already been initialized). This class has a series of operations on the map.

I need to write a unit test. It would get the private variable, mock(or spy) it, perform some operations on it, and verify the order of operations. What is the best way?

public class A{
   private Map<String, String> map = new Map()<>;

   }
   public method method1(){
     map.put("a", "A");
   }       

   public method method2(){ 
     if(map.size() > 0){
        map.put("b", "B");
     }

}
...
public class UnitTester{
@Test
public void test(){
    A ainstance = new A();
    Map<String,String> mock = mock(Map.class); //OR Map<String,String> mock = spy(Map.class); 

    Field f= A.class.getDeclaredField("map");
    f.setAccessible(true);
    f.set(ainstance, mock);

    ainstance.method1();
    ainstance.method2();

    InOrder inOrder = inOrder(mock);
    inOrder.verify(mock, times(2), put(anyString(), anyString()));  //Does not work

    }
}

map.put does not add anything into the map. Not sure if this is because it is a reflection object or what it is.





Aucun commentaire:

Enregistrer un commentaire