Mocking Static Functions in Android

六月ゝ 毕业季﹏ 提交于 2021-02-05 06:40:31

问题


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' with androidTestImplementation '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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!