首页 > 解决方案 > 如何在 Kotlin 中使用 Junit 5 的 TempDir?

问题描述

我想将以下(工作)java 测试转换为 Kotlin:

package my.project;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class MyTempFileTest {

    @TempDir
    public File tempFolder;

    @Test
    public void testTempFolder() {
        Assertions.assertNotNull(tempFolder);
    }

    @Test
    public void testTempFolderParam(@TempDir File tempFolder) {
        Assertions.assertNotNull(tempFolder);
    }
 }

使用 IntelliJ 的内置转换器,它变为:

package my.project

import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File

class MyTempFileTest {
    @TempDir
    var tempFolder: File? = null
    
    @Test
    fun testTempFolder() {
        Assertions.assertNotNull(tempFolder)
    }

    @Test
    fun testTempFolderParam(@TempDir tempFolder: File?) {
        Assertions.assertNotNull(tempFolder)
    }
}

但这无法初始化:

org.junit.jupiter.api.extension.ExtensionConfigurationException: @TempDir field [private java.io.File my.project.MyTempFileTest.tempFolder] must not be private.

然而,放在public前面var并没有什么区别。我收到相同的错误消息,IntelliJ 甚至建议再次删除明显的“冗余” public

标签: kotlinjunit5temporary-filestempdir

解决方案


You have to annotate the field with @JvmField so that the Kotlin compiler generates an actual public field, instead of getter and setter:

@TempDir
@JvmField
var tempFolder: File? = null

推荐阅读