Powermockito verifystatic

时间:2017-12-11 20:29:07

标签: java mockito powermock powermockito

我有一个遗留类,它有一个我需要测试的静态void方法:

public class A {

    public static void renameTo()
    {
        String ext = "." + this.fileName + ".backup";
        for (File file : getCSVFile()) {
            f.renameTo(new File(file.getAbsolutePath() + ext));
        }

    public static File[] getAllFiles()
    {
        //logic to read the CSV files from the class path
    }


}

现在我已经使用PowerMockito为它编写了一个测试用例,看起来像这样。现在的问题是,即使renameTo()仅被调用,如果我调用PowerMockito.verifyStatic( Mockito.times(10)),测试仍然通过

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
@PowerMockIgnore("javax.management.*")
public class ATest {

    @Test
    public void testRenameTo() throws Exception {
        PowerMockito.mockStatic(A.class);
        A.renameTo();
        PowerMockito.verifyStatic( Mockito.times(1));
        //PowerMockito.verifyStatic( Mockito.times(5));//Passes even though the mehod is called only once    
        //PowerMockito.verifyStatic( Mockito.times(10);//Passes even though the mehod is called only once    
    } 
}

有人可以对这个问题有所了解吗?我可能做错了什么?

1 个答案:

答案 0 :(得分:2)

根据documentation,在首先需要调用verifyStatic之后,调用A.renameTo()告诉它要验证哪个静态方法。例如:

// run test
A.renameTo();

// verify interaction
PowerMockito.verifyStatic(A.class, Mockito.times(1));
A.renameTo();