问题
Is there any way I can Mock Static Function in Android using any Mocking Framework. Mockito can mock classes but is insuffiecient to mock Static functions.
Any help will be highly appreciated.
Thanks in Advance
回答1:
Mocking works by using the concepts of Object Orientation, Inheritance etc....
Basically by overriding certain methods & behaviour in objects / instances that look like real objects, because they are subclasses of these real objects.
In other words, the mocking part comes in overriding methods on instances.
It is not possible to override a static method (afaik).
Therefore mocking of static calls is not easy (if even possible).
EDIT - I was wrong...
As it turns out, I was wrong in my above statement that it is not possible.
I should have searched this site for duplicate questions. See below for some links to frameworks that claim to do this for you in some cases. Since they work with bytecode, I'm not sure they will work properly on Android (ymmv).
Mocking Static Methods
How can I easily mock out a static method in Java (jUnit4)
(thanks to Rohit for forcing me to reassess my beliefs)
回答2:
Please try this instead: https://bintray.com/linkedin/maven/dexmaker-mockito-inline-extended
It helps me successfully mock the static method in the Android Instrumented Tests, but note that this feature requires running on a device with at least Android P.
Here is what I did:
Replace the
androidTestImplementation 'org.mockito:mockito-android:2.28.0'
withandroidTestImplementation 'com.linkedin.dexmaker:dexmaker-mockito-inline-extended:2.28.0'
Then mock the static method like this:
static class StaticTrojan { static String staticOpen() { return "horse"; } } @Test public void testStubbingStaticMethod() { MockitoSession session = mockitoSession().spyStatic(StaticTrojan.class).startMocking(); try { when(StaticTrojan.staticOpen()).thenReturn("soldiers"); assertEquals("soldiers", StaticTrojan.staticOpen()); } finally { session.finishMocking(); } // Once the session is finished, all stubbings are reset assertEquals("horse", StaticTrojan.staticOpen()); }
来源:https://stackoverflow.com/questions/14703391/mocking-static-functions-in-android