Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 653
Iker Aguayo Avatar asked Oct 09 '14 09:10

Iker Aguayo


1 Answers

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;
like image 69
lance-java Avatar answered Sep 18 '22 12:09

lance-java