简体   繁体   中英

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 void method1(){
     map.put("a", "A");
   }       

   public void 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 there is a different cause to that.

Instead of using reflection manually you can take advantage of the annotations. Also your should change a bit the way you verify. Finally i would use use Spy instead of Mock as it is a bit more suitable in my opinion:

public class UnitTester{

@InjectMocks
private A aInstance;

@Spy
private Map mapSpy = new HashMap();

@Before
public void init(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void test(){
    // Act   

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

    InOrder inOrder = inOrder(mapSpy);
    inOrder.verify(mapSpy).put("a", "A"));      
    inOrder.verify(mapSpy).put("b", "B"));     
}

I have written an article on Mockito Spying and InOrder Verification if you need a further read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM