【发布时间】:2015-10-22 23:22:44
【问题描述】:
我在使用 Mockito 时遇到了这种奇怪的行为,但我不确定这是否是预期的行为 :-(。以下代码是我想出的一个虚构的 Java 代码来强调这一点。
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 无法读取源代码,它依赖于代码的静态状态来记录每次调用应返回的内容。但是这种行为完全让我感到困惑,因为当它应该为一组它没有编程的参数发送空或空对象时,它会为不同的参数返回相同的对象。 我将 Java 1.7.0_79 和 Mockito 1.10.19 与 Junit 4.11 一起使用。 我是否遗漏了一些重要的东西,或者有人可以解释一下这种行为吗?
【问题讨论】: