Aequitas
Aequitas

Reputation: 2265

How do you bypass static method calls?

I have this line which is interferring in a unit test:

OtherClass.staticMethodThatWillErrorIfCalled().isAvailable();

If it wasn't static I could just mock OtherClass and then do this:

Mockito.doReturn(null).when(mockedOtherClass).staticMethodThatWillErrorIfCalled();
Mockito.doReturn(true).when(mockedOtherClass).isGuiMode();

and the fact that it will error if called makes my attempts at using powermockito futile.

I'm not sure how I can do this. All I want to do is skip over this line (it's an if check) and continue on as if it had returned true. What is the best way to do this?

Upvotes: 0

Views: 1883

Answers (1)

Jose Martinez
Jose Martinez

Reputation: 12022

I would require more info to give a more specific answer but this is what I am thinking...

First tell PowerMockito that you will be mocking a static method in OtherClass.

@RunWith(PowerMockRunner.class)
@PrepareForTest(OtherClass.class)

These are class level annotations that go on your unit testing class.

Then mock what to do when that method is called.

PowerMockito.mockStatic(OtherClass.class);
Mockito.when(OtherClass.isAvailable()).thenReturn(Boolean.TRUE);

Do this in your @Before method on your unit testing.

Upvotes: 1

Related Questions