Setting up Powemockito for static mocking

前端 未结 3 1005
感情败类
感情败类 2021-02-08 13:29

I would like to make use of Powermock with Mockito to mock some static method calls. I have followed instructions and examples from SO as well as the PowerMock Getting Started

相关标签:
3条回答
  • 2021-02-08 13:53

    Make sure powermockito and mockito versions aligned as in this chart - https://github.com/powermock/powermock/wiki/Mockito#supported-versions,

    Easy way to find is,

    mvn dependency:tree | grep mockito
    [INFO] |  \- org.mockito:mockito-core:jar:1.8.5:compile
    [INFO] +- org.mockito:mockito-all:jar:1.9.5:compile
    [INFO] +- org.powermock:powermock-api-mockito:jar:1.5.6:compile
    

    In my case, powermock 1.5.6 and mockito 1.9.5 were aligned but had to change to use mockito 1.8.5, as someone else in the dependency was already using mockito 1.8.5.

    Following combination perfectly works for me,

    mvn dependency:tree | grep mockito
    [INFO] |  \- org.mockito:mockito-core:jar:1.8.5:compile
    [INFO] +- org.mockito:mockito-all:jar:1.8.5:compile
    [INFO] +- org.powermock:powermock-api-mockito:jar:1.4.9:compile
    
    0 讨论(0)
  • 2021-02-08 13:53

    Probably, the versions of Powermock and Mockito are not compatible. Fix that and it won't be a n issue anymore.

    Mockito                     PowerMock
    1.10.8+                     1.6.2+
    1.9.5-rc1 - 1.9.5           1.5.0 - 1.5.6
    1.9.0-rc1 & 1.9.0           1.4.10 - 1.4.12
    1.8.5                       1.3.9 to 1.4.9
    1.8.4                       1.3.7 & 1.3.8 
    1.8.3                       1.3.6
    1.8.1 & 1.8.2               1.3.5
    1.8                         1.3
    1.7                         1.2.5
    

    See: https://github.com/powermock/powermock/wiki/Mockito#supported-versions

    0 讨论(0)
  • 2021-02-08 13:59

    If you are using a static mock object, in your PrepareForTest annotation, add the class that is USING the static object in addition to the static class itself. If the class you are testing needs to use this static, add the current class to the annotation. You don't actually mock the class, but it needs to be in the annotation for the static to hook in. It sounds weird, but it works.

    When adding multiple classes into the annotation you can have them inside {} and seperated by commas. For example if your static class is StaticA.class and the class using the static is CallerOfStatic.class you can use:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({StaticA.class, CallerOfStatic.class})
    
    0 讨论(0)
提交回复
热议问题