'how to mock global variable in Mockito

I have a global variable global.

My method has a line:

global.getListOfObjects()

I am trying to write a unit test and keep getting a NPE on the above line. How can i mock a global variable?

I am using Mockito and PowerMock.



Solution 1:[1]

These are the things you could do, if I understand your question correctly:

  1. Use setter method of that property in your source class. yourSourceClass.setGlobal(somethingYouNeed);

  2. If that is a public member, you can assign that public member value, from your test class. Like: yourSourceClass.global = <somethingYouNeed>;

Thanks.

Solution 2:[2]

Use must have the mock object of the same class as below

@InjectMock

ABCClass abc;

Now you can set global variable as abc.global = value in the test case where you need this value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3148615
Solution 2 Narender Gusain