Question

I'm still learning junit and I want to know how to write a junit test case for this problem. I'm using emma plugin to run coverage too. what do I do after I set values to (strings) path and name? in @Test

public static void createReport(final String path, final String name) throws IOException {
        File outDir = new File("Out");
        if (!outDir.exists()) {
            if (!outDir.mkdir()) {
            }
        }
}

Also do I need to use assertEquals after I set the values of the parameters?

Was it helpful?

Solution

If, instead, you use outDir.mkdirs() (which creates the folders if they don't exist) then Emma will not complain about the line not being covered by tests.

If you wanted to be very thorough, the way you'd test your code would be to run it with the directory purposely missing and check it's created. Either delete the output folder as part of the test:

File outDir = new File("Out")

/* You will probably need something more complicated than
 * this (to delete the directory's contents first). I'd
 * suggest using FileUtils.deleteDirectory(dir) from
 * Apache Commons-IO.
 */
outDir.delete();

// Prove that it's not there
assertFalse(outDir.exists());

createReport(...);

// Prove that it has been created
assertTrue(outDir.exists());

Or write the report into a temporary folder, if that option's available to you.

OTHER TIPS

My recommendation will be to use a temporary folder in order to leave the place clean after the test:

@Rule
public TemporaryFolder folder = new TemporaryFolder();

You can use this object to define a new path folder.

File tmpFolder = folder.newFolder("subfolder");
File tmpFile = new File(tmpFolder.getAsbolutePath(),"newFileName");

All you have to do is to call your method with this object:

obj.createReport(tmpFolder.getAbsolutePath(), tmpFile.getAsbolutePath() )

Then in you unit test you can check that the directory has been created:

Assert.asserttrue(tmpFolder.exists());
Assert.asserttrue(tmpFile.exists());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top