bca
bca

Reputation: 464

PowerMock spy calls original method but returns mocked value

I have following method which I mocked private method foo.

public class Foo { 
    public int x;

    public void init() {
        x = foo();
    }

    private int foo() {
        System.out.println("shouldn't print this");
        return 11;
    }
}

When I mocked the method as following:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Main.class, Foo.class})
public class MainTest {

@Test
public void foo() throws Exception {
    Foo f = PowerMockito.spy(new Foo());
    PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(f);
    PowerMockito.when(f, "foo").thenReturn(42);

    Main m = new Main();
    m.f.init();
    System.out.println(m.f.x);
}

}

It prints 42 instead of 11 which is correct but it also prints shouldn't print this.

Is it possible to mock private method without having call to that method?

Upvotes: 0

Views: 115

Answers (1)

Ratish Bansal
Ratish Bansal

Reputation: 2442

shouldn' print this is getting printed because of the below line.

PowerMockito.when(f, "foo").thenReturn(42);

Instead, change the line something like

PowerMockito.doReturn(42).when(f,"foo");

Upvotes: 2

Related Questions