0

I try to learn PowerMockitoand write a demo

This the parent class A

public abstract class A {
    protected String getRoot(Long id) {
        if (id == 0) {
            return "root";
        }
        return "not root";
    }
}

And this is the childA

public class ChildA extends A {
    private String info;
    public String getRootInfo(Long id) {
        String rootInfo = getRoot(id);
        return rootInfo;
    }

    private void initRootInfo(String info) {
        this.info = info;
    }
}

And now i want to mock the method A::initRootInfo,so i write a test case like this

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, ChildA.class})
public class ChildATest {

    @Spy
    @InjectMocks
    private ChildA childA = PowerMockito.spy(new ChildA());

    @Test
    public void getRootInfoUT() throws Exception {
        PowerMockito.doNothing().when(childA, "initRootInfo", Mockito.anyString());

        String rootInfo = childA.getRootInfo(0L);
        Assertions.assertEquals("root", rootInfo);
    }
}

When i run the test case, the PowerMockito call the real method initRootInfo, so that i get a little bit confused why the A::initRootInfo will be called really, shouldn't it be mock and replaced by PowerMockito? is there have something wrong i use PowerMockito?

How to mock private method by PowerMockito correctly

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 1
    Just to mention that this is a usually a bad practice. This ties your test to the implementation rather than testing the behaviour, so if an implementation changes, your tests will need to change considerably too. I'm not saying this is always wrong, but it should be used only in extreme rare cases. – Augusto Oct 29 '22 at 10:39
  • Why do you have `@Spy` AND assign `PowerMockito.spy`? Not sure if a dupe: https://stackoverflow.com/q/74027324/112968 – knittl Oct 29 '22 at 20:35
  • @Augusto This is just a demo, i just want to test how to mock private method in InjectMocks decorate's class – Yi Zhou Oct 31 '22 at 01:41

0 Answers0