Writing unit tests for classes that operate on files has always been a little weird. Every developer & their dog has their own way of either abstracting themselves from the file system (ala Spring’s Resource types) or by creating some sort of a file system sandbox that is cleaned up at the end of the test - after all we don’t want to litter temp directories with files that will never be used again, do we?

With JUnit’s 4.7 release there is now a new entrant in the game: enter the TemporaryFolder Rule. It allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails). No more writing my own sandbox classes.

@Rule
public TemporaryFolder folder = new TemporaryFolder();

@Test
public void shouldDownloadFileUsingPublicLink() throws Exception {

  String bucketName = "test-" + RandomStringUtils.randomAlphabetic(10);

  Service service = new HttpClientService(credentials);
  service.createBucket(bucketName);

  File file = folder.newFile("foo.txt");
  FileUtils.writeStringToFile(file, RandomStringUtils.randomAlphanumeric(100));
  service.createObject(bucketName, file.getName(), file);

  String publicUrl = service.getPublicUrl(bucketName, file.getName(),
    new DateTime().plusDays(5));

  File saved = folder.newFile("saved.txt");
  Files.writeToFile(new URL(publicUrl).openConnection().getInputStream(), saved);
  assertEquals("Corrupted file", Files.computeMD5(file), Files.computeMD5(saved));

  service.deleteObject(bucketName, file.getName());
  service.deleteBucket(bucketName);
}