jenkins执行单元测试,会产生大量临时文件,要及时删除,不然会把inode耗尽

  jenkins的build命令:clean test -U findbugs:findbugs pmd:pmd sonar:sonar -Djava.io.tmpdir=/tmp/ -Dsonar.projectKey=xxxxx -Dsonar.projectName=xxxxxx -Dsonar.branch=xxxxx,这条命令执行单测的时候,会产生大量的临时文件到linux的/tmp/目录,日积月累,会最终消耗殆尽inode,从而不能使用硬盘再创建文件和文件夹

  原因:在做java单元测试的时候,创建了一些临时文件,没有及时删除:https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/

  You can remove the burden of deleting temporary files and folders from your test code by using a JUnit TemporaryFolder Rule. Rules themselves are new in JUnit 4.7 and are used to change the behavior of tests. For example, the following test creates and deletes a temporary file and folder:

  In order to enable this feature, you must use the annotation @Rule on the declaration of the TemporaryFolder instance variable. The TemporaryFolder creates a folder in the default temporary file directory specified by the system property java.io.tmpdir. The method newFile creates a new file in the temporary directory and newFolder creates a new folder.

  When the test method finishes, JUnit automatically deletes all files and directories in and including the TemporaryFolder. JUnit guarantees to delete the resources, whether the test passes or fails.

package test;
 
import java.io.File;
import java.io.IOException;
 
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
 
public class TestTemporaryFolderRule {
    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();
 
    @Test
    public void testInTempFolder() throws IOException {
        File tempFile = testFolder.newFile("file.txt");
        File tempFolder = testFolder.newFolder("folder");
        System.out.println("Test folder: " + testFolder.getRoot());
        // test...
    }
}

  

What is the correct way to write to temp file during unit tests with Maven?

Tests fail when java.io.tmpdir does not exist:https://ops4j1.jira.com/browse/PAXEXAM-294

  

Java.io.tmpdir介绍: https://www.cnblogs.com/nbjin/p/7392541.html

原文地址:https://www.cnblogs.com/shengulong/p/9069251.html