Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用PowerMockito模拟构造函数_Java_Android_Mockito_Powermockito - Fatal编程技术网

Java 如何使用PowerMockito模拟构造函数

Java 如何使用PowerMockito模拟构造函数,java,android,mockito,powermockito,Java,Android,Mockito,Powermockito,我第一次尝试用PowerMockito模拟类构造函数,但它不起作用。我目前的代码是: public class Bar { public String getText() { return "Fail"; } } public class Foo { public String getValue(){ Bar bar= new Bar(); return bar.getText(); } } @RunWith(

我第一次尝试用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”。我的问题在哪里?

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

@PrepareForTest(Foo.class)
而不是

@PrepareForTest(Bar.class)

别忘了这个!