Iker Aguayo
Iker Aguayo

Reputation: 4115

Mocking static fields with Mockito

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).

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)

I tried some things PowerMockito, the WhiteBox, but without success. Now I have done this, but I get the same 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

Upvotes: 6

Views: 20641

Answers (1)

lance-java
lance-java

Reputation: 27994

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;

Upvotes: 6

Related Questions