【问题标题】:Mocking files and unit tests with temporaryFolder使用temporaryFolder 模拟文件和单元测试
【发布时间】:2021-08-26 16:44:55
【问题描述】:

我有一个方法是搜索并将目录中的所有 java 文件添加到列表:

public List<File> findJavaFiles(File root, String path) {
    String suffix = ".java";
    List<File> list = new ArrayList<>();
    if (root.isDirectory()) {
        File[] files = root.listFiles();
        if (files != null) {
            for (File file : files) {
                list.addAll(findJavaFiles(file, suffix));
            }
        }
    } else if (root.getName().endsWith(suffix)) {
        list.add(root);
    }
    return list;
}

它有效,但问题是我想创建单元测试(我开始“有趣”地使用模拟测试)。我知道我应该使用临时文件夹和模拟 java 文件,所以我有这样的东西:

@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

@Before
public void setUp() throws IOException {
file1 = mock(File.class);
    when(file1.getName()).thenReturn("file1.java");
    when(file1.length()).thenReturn(1L);
    file2 = mock(File.class);
    when(file2.getName()).thenReturn("file2.java");
    when(file2.length()).thenReturn(5L);
    file3 = mock(File.class);
    when(file3.getName()).thenReturn("file3.java");
    when(file3.length()).thenReturn(3L);
    file4 = mock(File.class);
    when(file4.getName()).thenReturn("file4.jpg");
    when(file4.length()).thenReturn(10L);
    temporaryFolder.newFile(file1.getName());
    temporaryFolder.newFile(file2.getName());
    temporaryFolder.newFile(file3.getName());
    temporaryFolder.newFile(file4.getName());

和单元测试:

@Test
public void findJavaFilesIsCorrect() {
    //given
    List<File> expectedResult = List.of(file1, file2, file3);
    //when
    when(fileService.findJavaFiles(ArgumentMatchers.anyString())).thenCallRealMethod();
    List<File> result = fileService.findJavaFiles(System.getProperty(System.getProperty("java.io.tmpdir")));
    //then
    Assert.assertEquals(expectedResult, result);
}

测试失败...结果列表为空...但我不知道为什么

【问题讨论】:

    标签: java testing mocking temporary-files


    【解决方案1】:

    您需要设置 java.io.tmpdir 的值。

    【讨论】:

    • 嗯...不,我应该在哪里做?
    • 你是如何运行程序的。你能打印/检查值吗?
    • 我在其他方法中使用该方法
    • 公共地图 countCreatedFilesByWeekday(String path) { List javaFiles = findJavaFiles(path); return javaFiles.stream() .map(this::getFileCreationDate) .map(Date::new) .map(this::getDayFromDate) .collect(Collectors.groupingBy(s -> s, Collectors.counting()));
    • @Anonymous,看起来他们已经编辑为答案,这很好。在我查看时,它只是对原始帖子的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多