使用真实实现的Mockito模拟对象

nui*_*cca 5 java junit mockito

为什么要mockMap使用真正的实现?我该如何防止这种情况?

在方法testFirstKeyMatch中

when(mockMap.keySet().toArray()[0])...
Run Code Online (Sandbox Code Playgroud)

抛出ArrayIndexOutOfBoundsException:运行测试时为0.

MaxSizeHashMap是一个最大大小为7的LinkedHashMap,当我尝试添加更多内容时抛出一个IndexOutOfBoundsException.

配置文件记录对此不重要的内容.

SuperClass.java

public class SuperClass {

protected String[] days;
protected MaxSizeHashMap<String, String> map;

public SuperClass() {
    days = new String[7];
    map = new MaxSizeHashMap<String, String>();
    //...
}

void updateDays() {

    cal = Calendar.getInstance();

    for (int i = 0; i < 7; i = i + 1) {

        //adds short names "Mon", "Tue", ... to days
        days[i] = cal.getDisplayName(Calendar.DAY_OF_WEEK, 
                Calendar.SHORT, Locale.US);

        cal.add(Calendar.DATE, 1);
    }
}

void firstKeyMatch(Profile profile) {

    updateDays(); 

    //checks if first key of map is not same as days[0]
    if (days[0] != map.keySet().toArray()[0]) {

        profile.add();

        //...
     }
 }
 }
Run Code Online (Sandbox Code Playgroud)

SuperClassTest.java

@RunWith(MockitoJUnitRunner.class)
public class SuperClassTest {

@InjectMocks
private SuperClass spr = new SuperClass();

@Mock
private MaxSizeHashMap<String, String> mockMap;

@Mock
private Profile mockProfile;

//...

@Test
public void testFirstKeyMatch() {   

    when(mockMap.keySet().toArray()[0]).thenReturn(spr.days[0]);

    verify(mockProfile, never()).add();

}
}
Run Code Online (Sandbox Code Playgroud)

Mor*_*fic 3

根据文档,mockito 对于模拟的隐式行为是返回默认值

默认情况下,对于所有返回值的方法,模拟将根据需要返回 null、原始/原始包装器值或空集合。例如,0 表示 int/Integer, false 表示 boolean/Boolean。

因此,您mockMap.keySet()将返回一个空的哈希集,然后将其转换为空数组并尝试检索(不存在的)第一个元素,即 IOOBE。

调试器

总之,mockito 没有使用真正的实现,但它的行为正常,正如它应该的那样。

您没有发布 的​​整个构造函数SuperClass,但可能在实例化映射后,您还用值填充它。如果这是真的,那么人们可以说异常实际上证明了mockito没有使用真正的实现,因为你真的会得到第一个元素。

至于解决方案,已经建议使用您需要的任何数据返回您自己的哈希集(学分归 Abubakkar):

when(mockMap.keySet()).thenReturn(new HashSet(Arrays.asList("your day string")));
Run Code Online (Sandbox Code Playgroud)