【问题标题】:How to mock constructor with PowerMockito如何使用 PowerMockito 模拟构造函数
【发布时间】:2016-12-12 22:32:09
【问题描述】:

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

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”。我的问题在哪里?

【问题讨论】:

    标签: java android mockito powermockito


    【解决方案1】:

    好的,找到答案了,你需要打电话给

    @PrepareForTest(Foo.class)
    

    而不是

    @PrepareForTest(Bar.class)
    

    【讨论】:

    • 别忘了这个!
    猜你喜欢
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多