基本的 thenReturn 在 Eclipse 的 Mockito 中不起作用
Basic thenReturn not working in Mockito in Eclipse
很抱歉提出这样一个基本问题。对于为什么我不能终生在我的模拟上配置 thenReturn,我只是有点沮丧。在 Eclipse 单元测试视图中,我得到了这个失败跟踪:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() request an argument which has to be 'a mthod call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
但这是我的代码,实际上只是一个简单的 POJO:
ConnectionDetails mockDetails = mock(ConnectionDetails.class);
when(mockDetails.getHostName()).thenReturn("hello");
assertEquals("hello", mockDetails.getHostName());
这应该没问题吧?
故障痕迹如下:
方法声明:
public final String getHostName() {
return hostName;
}
感谢您指出问题出在我的方法声明中的 "final"。
Gavin 在评论中解决:
Have you checked that getHostName isn't final?
Mockito 模拟是代理(有效动态生成的子类)并且标记方法 final
防止它们触发 Mockito 的覆盖。因此,您的测试调用了真正的方法,Mockito 给出了 MissingMethodInvocationException。
很抱歉提出这样一个基本问题。对于为什么我不能终生在我的模拟上配置 thenReturn,我只是有点沮丧。在 Eclipse 单元测试视图中,我得到了这个失败跟踪:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() request an argument which has to be 'a mthod call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
但这是我的代码,实际上只是一个简单的 POJO:
ConnectionDetails mockDetails = mock(ConnectionDetails.class);
when(mockDetails.getHostName()).thenReturn("hello");
assertEquals("hello", mockDetails.getHostName());
这应该没问题吧?
故障痕迹如下:
方法声明:
public final String getHostName() {
return hostName;
}
感谢您指出问题出在我的方法声明中的 "final"。
Gavin 在评论中解决:
Have you checked that getHostName isn't final?
Mockito 模拟是代理(有效动态生成的子类)并且标记方法 final
防止它们触发 Mockito 的覆盖。因此,您的测试调用了真正的方法,Mockito 给出了 MissingMethodInvocationException。