I was surprised to see
this beautiful feature in JUnit and it helped to ease to lots of constrains I
face while writing JUnit tests.
I basically follow TDD and
as you guys know we focus more on writing tests, hence it is necessary to use
some shortcuts availed by the tools like JUnit to make the process fast.
Recently I had an issue where I had to create and delete a file before and
after every test executes. I did that using @Before and @After annotation of
Junit and it worked, however I was looking for more of a generic way to do this at
one place. As I started googling I came across this post, which is amazing,
After reading the block I
know how I can generalize my creating and deleting of a temporary file or
folder (I decided to go with a temporary folder and a file inside it, which
looks more readable and oganized).
The JUnit class:
public class TemporaryFolderTestCase { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setupTemporaryFolder() throws IOException { temporaryFolder.newFolder(); } @Test public void shouldCheckFileInsideTemporaryFolder() throws Exception { temporaryFolder.newFile("tempData"); File tempFile = new File(temporaryFolder.getRoot()+"\\tempData"); if(!tempFile.exists()) { fail("File does not exists " + tempFile.getName()); } } }
Rules can be used to add additional functionality to the test which will be executed with in the test class and for every tests included. It works based on the method interception techniques. The Rule is executed before and after the the test method executes.
Comments
Post a Comment