How to mock constructor with PowerMockito

时间秒杀一切 提交于 2019-12-29 07:44:09

问题


I'm trying to mock a class constructor with PowerMockito for first time, but it doesn't work. My current code is:

public class Bar {
    public String getText() {
        return "Fail";
    }
}

public class Foo {
    public String getValue(){
        Bar bar= new Bar();
        return bar.getText();
    }

}

@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar.class)
public class FooTest {
    private Foo foo;
    @Mock
    private Bar mockBar;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        PowerMockito.whenNew(Bar.class).withNoArguments().thenReturn(mockBar);
        foo= new Foo();
    }

    @Test
    public void testGetValue() throws Exception {
        when(mockBar.getText()).thenReturn("Success");
        assertEquals("Success",foo.getValue());

    }
}

The test fails because the returned value is "Fail". Where is my problem?


回答1:


Okey, found the answer, you need to call to

@PrepareForTest(Foo.class)

instead of

@PrepareForTest(Bar.class)


来源:https://stackoverflow.com/questions/41110804/how-to-mock-constructor-with-powermockito

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