PowerMockito: NotAMockException on a mock

前端 未结 2 673
谎友^
谎友^ 2021-02-07 18:14

Bit of a complicated setup. Robolectric, PowerMockito rule-based config.

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sd         


        
相关标签:
2条回答
  • 2021-02-07 18:36

    I ran into this problem too. There is actually an issue on the PowerMock project: https://github.com/jayway/powermock/issues/593

    But no comments from any of the powermock developers.

    0 讨论(0)
  • 2021-02-07 18:37

    I cannot build your example, but I managed to write this minitest that produces a very similar problem:

    @RunWith(RobolectricGradleTestRunner.class)
    @Config(constants = BuildConfig.class, sdk = 21)
    @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
    @PrepareOnlyThisForTest({ServiceCallbackBase.class, Dummy.class})
    public class MainActivityTest {
    
        @Rule
        public PowerMockRule rule = new PowerMockRule();
    
        @Test
        public void test1() throws Exception {
            try {
                //This Mockito.withSettings() thing is important to make the test fail!
                ServiceCallbackBase callback = PowerMockito.mock( ServiceCallbackBase.class, Mockito.withSettings());
    
                callback.dispatchMessage(null);
                Mockito.verify(callback).dispatchMessage(null);
    
            } catch (Exception e){
                e.printStackTrace();
                Assert.fail();
            }
        }
    }
    

    (Note the Mockito.withSettings(), I don't know why but that makes the test to fail)

    Prints:

    org.mockito.exceptions.misusing.NotAMockException: 
        Argument passed to verify() is of type ServiceCallbackBase$$EnhancerByMockitoWithCGLIB$$62776c54 and is not a mock!
        Make sure you place the parenthesis correctly!
        ......
    

    Well, this absolutely looks as a classloading issue, mockito is comparing ServiceCallbackBase$$EnhancerByMockitoWithCGLIB$$etc.. loaded by Powermock with the same loaded by Robolectric (obviously returning false in that comparision)

    Then, I managed to make the test work simply adding "org.powermock.*"to the line @PowerMockIgnore... this is:

    @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*", "org.powermock.*"})
    

    This simple change made my test to work, and I really hope that make yours too.

    0 讨论(0)
提交回复
热议问题