2015-10-22 124 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

相關問題