PowerMockito whenNew not invoked when constructor is called

24 Views Asked by At

Here are my classes.

public class Foo {
  public Foo() {
  }
}
public class Bar {
  public Bar() {

  }

  public Foo getFoo() {
    return new Foo();
  }
}

This is my test.

@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar.class)
public class TestTest {

  @Test
  public void test() throws Exception {
    Foo mockFoo = PowerMockito.mock(Foo.class);
    PowerMockito.whenNew(Foo.class).withNoArguments().thenReturn(mockFoo);
    Bar bar = new Bar();
    Foo foo = bar.getFoo();
    assert(foo == mockFoo);
  }
}

An assertion error is thrown, but I expect being able to get the mockFoo from bar, given that

  1. PowerMockito has a designated mock behavior when Foo constructor is called
  2. Bar class calls Foo constructor
  3. Bar class is prepared for

Could someone help me understand what I'm doing wrong?

0

There are 0 best solutions below