java 使用 Mockito 模拟静态字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26274705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:37:16  来源:igfitidea点击:

Mocking static fields with Mockito

javaunit-testingmockingmockito

提问by Iker Aguayo

I have something like this (it is a third party library so I have to work with this design):

我有这样的东西(它是第三方库,所以我必须使用这个设计):

ClassA.conn1.getObjectA().getIntValue()

ClassA is a normal class, and inside it there is a public static field (conn1). This conn1 is a class which have a connection and some other values which are used in the application (in my case that ObjectA).

ClassA 是一个普通的类,里面有一个公共静态字段(conn1)。这个 conn1 是一个类,它有一个连接和一些在应用程序中使用的其他值(在我的例子中是 ObjectA)。

This value is passed as parameter in the dao I am mocking. That value is mocked as Matchers.anyInt() but I get a NullPointerException because conn1 is null (not the expected int)

这个值在我模拟的 dao 中作为参数传递。该值被模拟为 Matchers.anyInt() 但我得到一个 NullPointerException 因为 conn1 为空(不是预期的 int)

I tried some things PowerMockito, the WhiteBox, but without success. Now I have done this, but I get the same NullPointerException

我尝试了一些 PowerMockito,WhiteBox,但没有成功。现在我已经这样做了,但我得到了相同的 NullPointerException

Mockito.when(ClassA.conn1.getObjectA()).thenReturn(new ObjectA(2));

The question is, how can I mock it to get the ObjectA or the int value of the ObjectA

问题是,我如何模拟它以获取 ObjectA 或 ObjectA 的 int 值

采纳答案by lance-java

import static x.y.z.Mockito.*;

ObjectA objectA = mock(ObjectA.class);
when(objectA.getIntValue()).thenReturn(1));

Conn conn1 = mock(Conn.class);
when(conn1.getObjectA()).thenReturn(objectA);

ClassA.conn1 = conn1;