简体   繁体   中英

Calling non mocked functions for a mocked object

import java.lang.Math;
import static org.mockito.Mockito.*;
import java.util.Map;
import java.util.HashMap;

public class MyClass
{
  class Test {
      int a = 10;
      Test() {}
  }    
  class OtherClass
  {
     public OtherClass()
     {}

     Map<String, Double> f() {
        System.out.print("Just for testing"); 
       return new HashMap<>();
     }

     Test getT() {
         return new Test();
     }

  }

  public static void main(String[] args)
  {
    OtherClass c = mock(OtherClass.class);
    Map<String, Double> test = c.f();
    System.out.println(test.size());
    MyClass.Test t = c.getT();
    System.out.println(t);
  }
}

In this example I have created mock object for OtherClass type. What strange for me that cf() returns empty Map, meanwhile c.getT() returns null. Could you please help me to understand this behavior?

If you do not provide a stub for Map , Mockito will return an empty map. This is a documented feature, confirmed by the JavaDocs :

By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (eg: 0, false, ... for int/Integer, boolean/Boolean, ...).

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