Sameer
Sameer

Reputation: 169

How to write JUnit test for API that copies directory to directory

I just want to write a JUnit test case that will just test whether my below code has successfully copied the directory to new directory.

File origPath = new File("/sourceDir/");

File newPath = new File("/destDir/");

try {
    FileUtils.copyDirectory(origPath, newPath);
    } catch (Throwable e) {

    }

Please suggest, how I can write a JUnit test or mock to test the above code.

Upvotes: 1

Views: 4269

Answers (4)

Andremoniy
Andremoniy

Reputation: 34920

A one simple solution is to check, whether all files from /sourceDir/ are present in the directory /destDir/:

File origPath = new File("/sourceDir/");
File newPath = new File("/destDir/");
for (File file : origPath.listFiles()) {
    assertTrue(new File(newPath, file.getName()).exists());
}

Upvotes: 3

looper
looper

Reputation: 1989

You need the TemporaryFolder Rule.

@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();

Then you create a new folder:

File source = tempFolder.newFolder();

Then you call the copyDirectory-method:

FileUtils.copyDirectory(source.getAbsolutePath(), source.getParent() + "/dest");

And then you can check, whether the folder exists:

new File(tempFolder.getRoot(), "dest").exists()

Upvotes: 5

Nick Holt
Nick Holt

Reputation: 34321

Unless there's a lot of non-IO logic in the copyDirectory method using mocks in any test is pointless as it will just test the code calls performs the operations it contains.

So the test is going to have to:

  • create a source directory and write a file to it.
  • create a destination directory.
  • invoke the copyDirectory method.
  • read the contents of the destination directory and assert the contents.
  • clean-up.

Upvotes: 2

assylias
assylias

Reputation: 328923

You can mock but this will only test you call some methods, not that it actually works, i.e. it looks more like an integration test and I would simply create a few real tests, such as:

  1. Check that a fake directory does not exist ("Asdlkjslajfrhg") try to copy it and make sure you get the right exception
  2. Create a fake directory, copy it and make sure the new directory has been created and is empty
  3. Create a fake directory and a few files with data inside, copy the directory and make sure the new directory has been created and contains all the files with the same content
  4. Make sure you clean everything after each test

Note: recent versions of JUnit include a TemporaryFolder class, which should help you handle most of the "faking directories" part. See also this post for an example.

Upvotes: 3

Related Questions