【问题标题】:Mocking an object that is created inside a method模拟在方法内创建的对象
【发布时间】:2020-07-05 20:32:31
【问题描述】:

待测方法

public class myclass{
public void findFile(final String directoryName, final DataImportMonitoringCronjobModel job)
    {
        File file = new File(directoryName);
        if (file.isDirectory())
        {
            final Date archiveDate = new Date(file.lastModified());
..}
}

如何从我的测试类中为文件对象创建模拟并满足 if 条件?

我尝试使用 PowerMockito,但无法满足 if 条件。

测试类

@Mock
private File file;
@Test
public void findFileTest() throws Exception
{
    
    PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
    PowerMockito.when(file.isDirectory()).thenReturn(true);
    myclass.findFile();
}

【问题讨论】:

  • 我不确定我是否理解。您从测试中返回的file 是什么?为什么不直接模拟 isDirectory 方法?
  • 我正在返回使用@Mock(已编辑)模拟过的文件 isDirectory 是 File.class 的一种方法。所以我们应该先实例化 tie 对象来使用方法 isDirectory
  • 为什么不模拟 isDirectory?
  • 我们该怎么做呢?我是编写测试用例的新手,这真的很有帮助。
  • 我认为大多数 PowerMock/PowerMockito 教程都涵盖了这一点,因为这是它所做的事情之一。

标签: unit-testing junit powermockito


【解决方案1】:

为什么要嘲讽? 使用真实的临时文件/目录进行测试。

JUnit5 有@TempDir

JUnit4 有@Rule TemporaryFolder

这样你可以获得真正的文件/文件夹,在你的方法中提供它,然后检查之后会发生什么。

【讨论】:

  • 因为 mock 方法比实际的文件 io 快,所以不需要实际的文件,如果你需要修改日期,你最终还是会 mock。
  • 并非总是如此。例如PowerMock 非常非常慢,在很多情况下处理真实文件会更快。
  • 我想看看基准测试显示被操纵的字节码是如何比磁盘访问慢的。
  • 你能帮我在上述情况下如何使用@Rule TemporaryFolder吗?
猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 2016-03-14
相关资源
最近更新 更多