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

前端 未结 5 1294
暗喜
暗喜 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:03

    ArtB,

    Just pasting the complete code which works fine in my Eclipse IDE. I have only changed the expectation i said in my last post. Good luck.

    import static org.hamcrest.core.Is.is;
    import static org.junit.Assert.assertThat;
    import static org.mockito.Matchers.anyInt;
    import static org.mockito.Matchers.anyString;
    import static org.powermock.api.support.membermodification.MemberMatcher.method;
    
    import java.util.Random;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(CodeWithPrivateMethod.class)
    public class PowerMock_Test {
    
        static boolean gambleCalled = false; 
    
        @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());
    
            PowerMockito.doReturn(true).when(spy, 
                   method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                    .withArguments(anyString(), anyInt());
    
            assertThat( PowerMock_Test.gambleCalled, is(false) );
            spy.meaningfulPublicApi();
            assertThat( PowerMock_Test.gambleCalled, is(false) );
        }
    }
    
    
    class CodeWithPrivateMethod {
    
        public void meaningfulPublicApi() {
            if (doTheGamble("Whatever", 1 << 3)) {
                throw new RuntimeException("boom");
            }
        }
    
        private boolean doTheGamble(String whatever, int binary) {
            Random random = new Random(System.nanoTime());
            boolean gamble = random.nextBoolean();
    
            System.err.println( "\n>>> GAMBLE CALLED <<<\n" );
            PowerMock_Test.gambleCalled = true;
    
            return gamble;
        }
    }   
    

提交回复
热议问题