Search code examples
javatemporary

How can I fill a temporary file with content?


I wrote a method which reads .properties files. I tested my method with real files on my pc and it worked. But now I want to use temporary files to make sure my unit tests works even if I delete my test resource. I tried:

@Rule
 public TemporaryFolder tmpFolder = new TemporaryFolder();

@Test
 public void loadPropertiesFromFile(){
     File tmpFile = File.createTempFile("test", ".properties", tmpFolder.getRoot()); 
}

But how can I write content in my tmpFile like "key1=foo1"?


Solution

  • Create a file called temp.properties, write your content (i.e. key1=foo1, etc) and use the File Api.

    @Test
     public void loadPropertiesFromFile(){
         File tmpFile = new File("temp.properties"); //put absolute path of file in argument.
    
     }