我用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