如何使用PowerMockito模拟构造函数 [英] How to mock constructor with PowerMockito

查看:817
本文介绍了如何使用PowerMockito模拟构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试第一次使用PowerMockito模拟类构造函数,但是它不起作用.我当前的代码是:

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());

    }
}

测试失败,因为返回的值为"Fail".我的问题在哪里?

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

推荐答案

Okey,找到了答案,您需要致电

Okey, found the answer, you need to call to

@PrepareForTest(Foo.class)

代替

@PrepareForTest(Bar.class)

这篇关于如何使用PowerMockito模拟构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆