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);
}
#1 by Felix on 26 September 2009 - 7:10 am
Quote
Interesting one. I was recently thinking something along theselines. I.e. your test framework acts as a container, instead of having a huge number of annotations.
#2 by Tom on 26 September 2009 - 8:58 pm
Quote
I’ve used the container approach previously as well with a good deal of success. I wonder how the rest of the rules that now come with JUnit will be used in the future.
#3 by Writings of french geek on 20 January 2010 - 8:40 am
Quote
I made a article about JUnit: Unit test except container J2EE with Spring and JNDI (here : http://bit.ly/798uHp )- The first solution consists in using the attribute defaultObject JndiObjectFactoryBean class which allows to change data source when call JNDI fails – The second consists in creating a class which will create for us context JNDI before using our services in the files of Spring configuration