0

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?

Aequitas
  • 2,205
  • 1
  • 25
  • 51
  • Please post more information, the whole unit test will be a good start. Is static method in class being tested? – Alex Buyny May 15 '15 at 01:16
  • Mock it. You *can* mock statics. – Dave Newton May 15 '15 at 01:21
  • @AlexBuyny i'm just executing a method in ClassToBeTested, but that method has the if check that I talk about which will call that static method that throws an error. I don't care about testing the static method or anything else in OtherClass I just want to get a true value returned so that I can execute and test a method in ClassToBeTested – Aequitas May 15 '15 at 01:21
  • @DaveNewton yes but because it is static it will call the method and so the error will be thrown. I want to skip over the method. – Aequitas May 15 '15 at 01:24
  • Have a look [here](http://codereview.stackexchange.com/questions/10359/unit-testing-legacy-code-with-static-classes) There are some approaches how to deal with statics in this article – Alex Buyny May 15 '15 at 01:26
  • I cannot make changes to either class, only to the unit test class – Aequitas May 15 '15 at 01:32
  • Maybe [this](http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) may help? – Alex Buyny May 15 '15 at 02:02
  • I've gone through that already, it also calls the static method. – Aequitas May 15 '15 at 02:12
  • ... You can mock static methods. I don't see what the issue is. – Dave Newton May 15 '15 at 10:49
  • the issue is that the static method is being called, say I have a sysout in the method, it will still display that message, which I don't want, I want to completely skip over it so the sysout is not displayed – Aequitas May 15 '15 at 22:45

1 Answers1

1

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.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68