Is there any way we can mock the static util method while testing in JUnit?
I know Powermock can mock static calls, but I don't want to use Powermock.
Are there any alternatives?
Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.
Power Mock gives you access to mock static methods, constructors etc. and this means that your code is not following best programming principles. Power Mock should be used in legacy applications where you cannot change the code which has been given to you.
The division of work between the two is that Mockito is kind of good for all the standard cases while PowerMock is needed for the harder cases. That includes for example mocking static and private methods.
(I assume you can use Mockito though) Nothing dedicated comes to my mind but I tend to use the following strategy when it comes to situations like that:
1) In the class under test, replace the static direct call with a call to a package level method that wraps the static call itself:
public class ToBeTested{ public void myMethodToTest(){ ... String s = makeStaticWrappedCall(); ... } String makeStaticWrappedCall(){ return Util.staticMethodCall(); } }
2) Spy the class under test while testing and mock the wrapped package level method:
public class ToBeTestedTest{ @Spy ToBeTested tbTestedSpy = new ToBeTested(); @Before public void init(){ MockitoAnnotations.initMocks(this); } @Test public void myMethodToTestTest() throws Exception{ // Arrange doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall(); // Act tbTestedSpy.myMethodToTest(); } }
Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists.com/mockito-spying
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With