【问题标题】:In powermockito how to mock an object which has another mocked object as the parameter?在 powermockito 中,如何模拟一个具有另一个模拟对象作为参数的对象?
【发布时间】:2021-09-15 04:13:22
【问题描述】:

我有这些方法

    public File getFileDetails(File file){
                  FileDetailMaker fileDetailMaker = new FileDetailMaker(getFileNumber(File.getName()));
                  return fileDetailMaker;
        }
        
        public String getFileNumber(String fileName){
                 return  fileName.substring(0,fileName.indexOf(".")).substring(0,8);
        }

我正在编写一个测试用例来测试 getFileDetails() 方法。如果我通过创建一个模拟“文件”对象并将“文件”的模拟作为参数发送来测试它,我会得到一个空指针异常,因为从模拟文件中无法获取子字符串。

我还通过

模拟了 FileDetailMaker 对象的创建
FileDetailMaker fileDetailMaker = Mockito.mock(FileDetailMaker.class);
            
PowerMockito.whenNew(FileDetailMaker.class).withAnyArguments().thenReturn(fileDetailMaker);
 

但我仍然收到空指针异常。所以你能帮我提出这个问题的建议吗

【问题讨论】:

    标签: java spring unit-testing mockito powermockito


    【解决方案1】:

    将此添加到您的测试用例中

    PowerMockito.when(file.getName()).thenReturn("filenameisthis.extension");
    

    file 是 File 类型的模拟对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2023-01-21
      相关资源
      最近更新 更多