【问题标题】:Mocking lombok @Getter fields with Mockito使用 Mockito 模拟 lombok @Getter 字段
【发布时间】:2018-03-17 19:53:31
【问题描述】:

我在我的一些静态字段上使用带有 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,但我不明白我为什么不是“在模拟上调用方法”。

有没有人成功模拟过 Lombok getter?

谢谢!

【问题讨论】:

  • getMyClass() 必须是静态的? mockito 支持静态方法模拟吗?

标签: java unit-testing mocking mockito lombok


【解决方案1】:

正如我在上面的评论中所说,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 ?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多