K
K
Konstantin17062016-12-28 16:33:31
Java
Konstantin1706, 2016-12-28 16:33:31

How to mock a static object with Mockito?

There is some object which contains a static field.
In the tests, I annotated the static field with Mock , and also indicated the following:

when(staticObject.getAnotherMethod()).thenReturn("test");

Moreover, in the tests themselves, the object got stuck, but when I get to the method call of this static field, it is null.
Stackoverflow suggests doing this procedure through PowerMock, but this does not suit me.
How to lock it correctly so that when calling the method (getAnotherMethod) it could return a known value?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2017-01-06
@Konstantin1706

Short answer: no way, Mockito only allows locking local fields/methods
Long answer: you need to edit the code under test to add the ability from the test to replace the default value of a static field with a locked one. Or convert a static field to a local field, which is the recommended approach when writing code under test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question