As mystarrocks mentioned in the comment, you can mock static methods using PowerMock, even you can test final class/method and private methods too!
From the documentation:
PowerMock is a framework that extend other mock libraries such as
EasyMock with more powerful capabilities. PowerMock uses a custom
classloader and bytecode manipulation to enable mocking of static
methods, constructors, final classes and methods, private methods,
removal of static initializers and more.
For example:
public class IdGenerator {
/**
* @return A new ID based on the current time.
*/
public static long generateNewId() {
return System.currentTimeMillis();
}
}
Then you can mock this static method using:
// This is the way to tell PowerMock to mock all static methods of a
// given class
mockStatic(IdGenerator.class);
/*
* The static method call to IdGenerator.generateNewId() expectation.
* This is why we need PowerMock.
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId);
Check Mocking static methods for the complete example.