我用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());
}
}
由於的Mockito無法讀取它依賴於代碼的記錄什麼應該在每次調用返回。但這種行爲完全困惑着我,因爲它返回不同的參數相同的對象靜止狀態下的源代碼當它應該爲一組參數發送null或empty對象時,它沒有編程。 我在使用Java 1.7.0_79和Mockito 1.10.19和Junit 4.11。 Am I錯過重要的東西,或者有人可以善意解釋這種行爲?
你提出了一個很好的觀點,即新的ArrayList().hashCode()返回1. +1。你和Sotirios的回答一起解釋了我究竟是什麼。謝謝。 –
Bunti