简体   繁体   English

如何使用PowerMockito模拟构造函数

[英]How to mock constructor with PowerMockito

I'm trying to mock a class constructor with PowerMockito for first time, but it doesn't work. 我是第一次尝试使用PowerMockito模拟类构造函数,但它不起作用。 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". 测试失败,因为返回值为“Fail”。 Where is my problem? 我的问题在哪里?

Okey, found the answer, you need to call to 哦,找到答案,你需要打电话给

@PrepareForTest(Foo.class)

instead of 代替

@PrepareForTest(Bar.class)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM