我有这个 TestNG 测试方法代码:
@InjectMocks
private FilmeService filmeService = new FilmeServiceImpl();
@Mock
private FilmeDAO filmeDao;
@BeforeMethod(alwaysRun=true)
public void injectDao() {
MockitoAnnotations.initMocks(this);
}
//... another tests here
@Test
public void getRandomEnqueteFilmes() {
@SuppressWarnings("unchecked")
List<Filme> listaFilmes = mock(List.class);
when(listaFilmes.get(anyInt())).thenReturn(any(Filme.class));
when(filmeDao.listAll()).thenReturn(listaFilmes);
List<Filme> filmes = filmeService.getRandomEnqueteFilmes();
assertNotNull(filmes, "Lista de filmes retornou vazia");
assertEquals(filmes.size(), 2, "Lista não retornou com 2 filmes");
}
我收到一个“org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
参数匹配器的使用无效!
0 个匹配器预期,1 个记录:”在此代码中调用 listAll() 方法时:
@Override
public List<Filme> getRandomEnqueteFilmes() {
int indice1, indice2 = 0;
List<Filme> filmesExibir = new ArrayList<Filme>();
List<Filme> filmes = dao.listAll();
Random randomGenerator = new Random();
indice1 = randomGenerator.nextInt(5);
do {
indice2 = randomGenerator.nextInt(5);
} while(indice1 == indice2);
filmesExibir.add(filmes.get(indice1));
filmesExibir.add(filmes.get(indice2));
return filmesExibir;
}
我很确定我在这里遗漏了一些东西,但我不知道它是什么!有人帮忙吗?
when(listaFilmes.get(anyInt())).thenReturn(any(Filme.class));
这就是你的问题。你不能使用any
在返回值中。any
是一个匹配器——它用于匹配参数值以进行存根和验证——并且在定义调用的返回值时没有意义。您需要显式返回一个 Filme 实例,或将其保留为空(这是默认行为,这会破坏存根点)。
我应该指出,使用真实列表而不是模拟列表通常是一个好主意。与您开发的自定义代码不同,列表实现是定义良好且经过良好测试的,并且与模拟列表不同,如果您重构被测系统以调用不同的方法,则真正的列表不太可能损坏。这是风格和测试理念的问题,但您可能会发现在这里使用真实的列表是有利的。
为什么上述规则会导致该异常?好吧,这个解释打破了 Mockito 的一些抽象概念,但是互利者的行为并不像你想象的那样 https://stackoverflow.com/q/22822512/1426891—它们将值记录到 ArgumentMatcher 对象的秘密 ThreadLocal 堆栈上并返回null
或其他一些虚拟值,并在调用中when
or verify
Mockito 看到一个非空堆栈,并且知道优先使用这些匹配器而不是实际参数值。就 Mockito 和 Java 评估顺序而言,您的代码如下所示:
when(listaFilmes.get(anyInt())).thenReturn(null);
when(filmeDao.listAll(any())).thenReturn(listaFilmes); // nonsense
自然地,Mockito 看到了any
匹配器,以及listAll
不接受争论,所以有预计有 0 个匹配者,已记录 1 个.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)