Mocked private method with PowerMock, but underlying method still gets called

前端 未结 5 1303
暗喜
暗喜 2020-12-14 07:50

I am trying to mock out a private method that is making a JNDI call. When that method gets called from a unit test, it throws an exception^. I would like to mock-out that me

5条回答
  •  情书的邮戳
    2020-12-14 08:09

    From the PowerMock Private Method Example:

    @RunWith(PowerMockRunner.class)
    // We prepare PartialMockClass for test because it's final or we need to mock private or static methods
    @PrepareForTest(PartialMockClass.class)
    public class YourTestCase {
    @Test
    public void privatePartialMockingWithPowerMock() {        
        PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());
    
        // use PowerMockito to set up your expectation
        PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
    
        // execute your test
        classUnderTest.execute();
    
        // Use PowerMockito.verify() to verify result
        PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
    }
    

    So to apply this to your code, I think it might become:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(CodeWithPrivateMethod.class)
    public class PowerMock_Test {
        @Test(expected = RuntimeException.class)
        public void when_gambling_is_true_then_always_explode() throws Exception {
            CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());
    
            PowerMockito.doReturn(true).when(spy, "doTheGamble", anyString(), anyInt());
    
    
    /* 1 */ PowerMockito.verifyPrivate(spy, times(0)).invoke("doTheGamble", anyString(), anyInt());            
            spy.meaningfulPublicApi();
    /* 2 */ PowerMockito.verifyPrivate(spy, times(2)).invoke("doTheGamble", anyString(), anyInt());            
        }
    }
    

    I just coded that in the editor here. No tests have actually been run, and no bugs have been harmed in the crafting of this code.

提交回复
热议问题