一、介绍

    PowerMockito 可以用来 Mock 掉 final 方法(变量)、静态方法(变量)、私有方法(变量)。想要使用 PowerMockito Mock掉这些内容,需要在编写的测试类上使用 注解:@RunWith(PowerMockRunner.class) 及 @PrepareForTest({First.class,Second.class}),对于注解 @PrepareForTest 网上有介绍说,可以不用注解到测试类上,直接注解到测试方法上,但是我在使用的时候不知道为什么不行,仅能注解到测试方法上。

二、调用别的类中的静态方法

(1) Mock 掉静态方法

   Mock 掉静态方法,需要在测试类上使用 @RunWith 及 @PrepareForTest 并 使用PowerMockito.mockStatic方法。

例子:

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

public class FileUtil extends FileUtils{
    
    private static final String FILE_EXTEND_SPLIT = ".";
    /***文件分割符****/
    public static final String FILE_SEPARATOR = "/";
    
    /**
     * 获取文件名(没有扩展内容)
     * @param fileName    文件名称
     * @return
     */
    public static String getNameNoExtend(String fileName){
        if(StringUtils.isNotBlank(fileName)){
            String name = fileName;
            int fileExtendSplitIndex = name.lastIndexOf(FILE_EXTEND_SPLIT);
            if(-1 != fileExtendSplitIndex && fileExtendSplitIndex != name.length()-1){
                name = name.substring(0, fileExtendSplitIndex);
            }
            return name;
        }
        return StringUtils.EMPTY;
    }
    
    /**
     * 判断文件是否是目录
     * @param file
     * @return
     */
    public static boolean isDirectory(File file){
        if(isExist(file) && file.isDirectory()){
            return true;
        }
        return false;
    }
    
    /**
     * 判断文件是否存在
     * @param file
     * @return
     */
    public static boolean isExist(File file){
        if(null != file && file.exists()){
            return true;
        }
        return false;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-09-15
  • 2021-10-31
  • 2022-01-17
  • 2022-01-01
  • 2021-04-30
  • 2022-12-23
猜你喜欢
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案