PowerMock + EasyMock: private void method without invokation

跟風遠走 提交于 2019-12-11 06:36:26

问题


Good time!

I need to substitute the class' private void method with a mock implementation, and can't to figure out how to do this. I've tried to use such a construction:

Test test = PowerMock.createPartialMock(Test.class, "setId");
PowerMock.expectPrivate(test , "setId", EasyMock.anyLong()).andAnswer(
    new IAnswer<Void>() {
        @Override
        public Void answer() throws Throwable {
            return null;
        }
    });
PowerMock.replay(test);

but the internal PowerMock's class called WhiteBox invokes my "setId" method which is wrong for my task. Could someone, please, suggest, how to avoid the method invokation and possibly to replace the method body with a custom one?


回答1:


Finally. I've got the solution. The problem was I missed the following annotations:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Test.class)

Anyway, it seems rather confusing that to make the PowerMock working I need to add some annotations. If that wasn't a legacy code I'd prefer Mockito.




回答2:


Not quite sure that I get the question. But for me code below works perfect and just string "Invoked!" is getting printed and if I remove test.setS(33L); test will fail with exception:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MainTest.Test2.class)
public class MainTest {

    @Test
    public void testName() throws Exception {
        Test2 test = PowerMock.createPartialMock(Test2.class, "setS");
        PowerMock.expectPrivate(test , "setS", EasyMock.anyLong()).andAnswer(
                new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        System.out.println("Invoked!");
                        return null;
                    }
                }).atLeastOnce();
        PowerMock.replay(test);
        test.setS(33L);
        PowerMock.verify(test);

    }


    class Test2 {
        long s;

        private long getS() {
            return s;
        }

        private void setS(long s) {
            this.s = s;
            System.out.println("Not this!");
        }
    }
}


来源:https://stackoverflow.com/questions/17027582/powermock-easymock-private-void-method-without-invokation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!