How to android unit test and mock a static method

后端 未结 4 375
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 22:39

Hi I really hope you can help me, I feel like I\'ve been pulling my hair out for days.

I\'m trying to write unit tests for a method A. Method A calls a static method

4条回答
  •  一生所求
    2020-12-15 23:05

    Static methods aren't related to any object - your helper.fetchUsernameFromInternet(...) is the same (but a bit confusing) as HelperUtils.fetchUsernameFromInternet(...) - you should even get a compiler warning due to this helper.fetchUsernameFromInternet.

    What's more, instead of Mockito.mock to mock static methods you have to use: @RunWith(...), @PrepareForTest(...) and then PowerMockito.mockStatic(...) - complete example is here: PowerMockito mock single static method and return object

    In other words - mocking static methods (and also constructors) is a bit tricky. Better solution is:

    • if you can change HelperUtils, make that method non-static and now you can mock HelperUtils with the usual Mockito.mock

    • if you can't change HelperUtils, create a wrapper class which delegates to the original HelperUtils, but doesn't have static methods, and then also use usual Mockito.mock (this idea is sometimes called "don't mock types you don't own")

提交回复
热议问题