2015-10-22 125 views
1

我用Mockito得到这个奇怪的行为,但我不知道它是否是任何方式的预期行为:-(。下面的代码是一个虚构的Java代码,我想出来突出显示点。Mockito对不同的参数值返回相同的结果

import org.junit.Test; 
import org.mockito.Mockito; 

import java.util.ArrayList; 
import java.util.HashSet; 
import java.util.List; 
import java.util.Set; 

import static org.hamcrest.MatcherAssert.assertThat; 
import static org.mockito.Mockito.when; 

public class StringServiceTest { 

    enum Style { 
     NONE, ITALIC, BOLD 
    } 

    private class StringService { 

     public List<String> getString(Set<String> words, long fontSize, Style fontStyle) { 
      return new ArrayList<>(); 
     } 
    } 

    @Test 
    public void testGetString() { 

     StringService stringService = Mockito.mock(StringService.class); 

     Set<String> words = new HashSet<>(); 
     List<String> sentence = new ArrayList<>(); 

     when(stringService.getString(words, 12L, Style.BOLD)).thenReturn(sentence); 

     List<String> result = stringService.getString(words, 234L, Style.ITALIC); 
     List<String> result1 = stringService.getString(words, 565L, Style.ITALIC); 
     List<String> result2 = stringService.getString(words, 4545L, Style.NONE); 

     assertThat("Sentences are different", result.hashCode() == result1.hashCode()); 
     assertThat("Sentences are different", result.hashCode() == result2.hashCode()); 
    } 
} 

由于的Mo​​ckito无法读取它依赖于代码的记录什么应该在每次调用返回。但这种行为完全困惑着我,因为它返回不同的参数相同的对象静止状态下的源代码当它应该为一组参数发送null或empty对象时,它没有编程。 我在使用Java 1.7.0_79和Mockito 1.10.19和Junit 4.11。 Am I错过重要的东西,或者有人可以善意解释这种行为?

回答

3

你只有存根下面的调用

when(stringService.getString(words, 12L, Style.BOLD)).thenReturn(sentence); 

这不符合任何你调用的

List<String> result = stringService.getString(words, 234L, Style.ITALIC); 
List<String> result1 = stringService.getString(words, 565L, Style.ITALIC); 
List<String> result2 = stringService.getString(words, 4545L, Style.NONE); 

对于unstubbed方法,使用的Mockito RETURN_DEFAULTS

每个模拟的默认Answer如果模拟不被截断。 通常它只是返回一些空值。

答案可以用来定义未打开的 调用的返回值。

此实现首先尝试全局配置。如果 没有全局配置则采用ReturnsEmptyValues(返回 零,空收藏,零点等)

换句话说,你的电话到getString中的每一个实际上是将一些空List( Mockito当前的实现返回一个新的实例LinkedList)。

由于所有这些List实例都是空的,它们都具有相同的hashCode

2

由于您正在嘲笑该类,它将返回一般返回值。这不是你想象的那样。在这种情况下,它是一个LinkedList。该列表hashCode取决于内容:

/** 
* Returns the hash code value for this list. 
* 
* <p>This implementation uses exactly the code that is used to define the 
* list hash function in the documentation for the {@link List#hashCode} 
* method. 
* 
* @return the hash code value for this list 
*/ 
public int hashCode() { 
    int hashCode = 1; 
    for (E e : this) 
     hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); 
    return hashCode; 
} 

如果打印出的hashCode,你会发现这是1

+0

你提出了一个很好的观点,即新的ArrayList ().hashCode()返回1. +1。你和Sotirios的回答一起解释了我究竟是什么。谢谢。 – Bunti

相关问题