我在我的某些静态字段上使用lombok的 @Getter
表示法:
public class A {
@Getter protected static MyClass myClass;
}
在单元测试时,我必须对这些静态字段的值模拟一部分的代码:
MyClass.getMyClass();
嘲笑,我在做:
mock(MyClass.class);
when(MyClass.getMyClass()).thenReturn(...);
但是,这样的模拟给出了以下错误。
[testng] org.mockito.exceptions.misusing.MissingMethodInvocationException:
[testng] when() requires an argument which has to be 'a method call on a mock'.
[testng] For example:
[testng] when(mock.getArticles()).thenReturn(articles);
[testng]
[testng] Also, this error might show up because:
[testng] 1. you stub either of: final/private/equals()/hashCode() methods.
[testng] Those methods *cannot* be stubbed/verified.
[testng] Mocking methods declared on non-public parent classes is not supported.
[testng] 2. inside when() you don't call method on mock but on some other object.
我必须达到条件2,但我不明白自己不是"在模拟上调用方法"。
有人成功嘲笑了伦波克·格特斯吗?
谢谢!
正如我在上面的评论中所说的那样,Mockito不支持模拟静态方法。
使用PowerMock
示例:
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class YourTestClass{
PowerMockito.mockStatic(A.class);
when(A.getMyClass()()).thenReturn(...);
}
另外,
MyClass.getMyClass();
getMyClass() belongs to class A or class Myclass ?