Write a file in JUnit test in resources folder

I've already tried this question , but I'm a bit lost with maven.

In a Maven project, I want to test a function that ultimately writes a text file to a specified path. My function signature boolean printToFile(String absolutePath)

(return value is success flag)

Q src/test/resources

I have an expected file; lets call it expected.txt

.

Using dependency apache.commons.commons-io

:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.3.2</version>
</dependency>

      

I want to call my function; create two objects File

and compare their contents:

@Test
public void fileCreationTest() {
  String outputPath = Thread.currentThread().getClass().getClassLoader().getResource("got.txt").getFile();
  myTestedObject.printToFile(outputPath);
  File got = new File(outputPath);

  String expectedFilePath = Thread.currentThread().getClass().getClassLoader().getResource("expected.txt").getFile();
  File expected = new File(expectedFilePath)

  boolean areEqual = FileUtils.contentEquals(got, expected);
  Assert.assertTrue(areEqual);

      

[Changed]
It's not a calling function question: If I call this from normal code, it works . But if I run my test, it fails (from maven or from my IDE). I think it has something to do with the test nature.

+3


source to share


1 answer


The following code doesn't make any sense to me (in test or otherwise):

String outputPath = Thread.currentThread().getClass().getClassLoader().getResource("got.txt").getFile();
myTestedObject.printToFile(outputPath);
File got = new File(outputPath);

      

The problem is that getResource

will return a URL

resource, which could be on the filesystem, in a JAR, or elsewhere. And it must exist for getResource

no return null

. This means that your test will have to overwrite it (and it is probably not writable).

Instead, you should do the following:

File got = File.createTempFile("got-", ".txt");
String outputPath = got.getAbsolutePath();
myTestedObject.printToFile(outputPath);

      



Also, for a file, expected

I find it better if you are using the test class classloader rather than the context classloader. It's also more readable:

String expectedFilePath = getClass().getClassLoader().getResource("expected.txt").getFile();
File expected = new File(expectedFilePath);

      

However, again you are making the assumption that the resource is loaded from the filesystem. So it might break if it isn't. Can you compare bytes with two InputStream

instead?

Finally, make sure the test is writing the file with the same encoding as your expected file and returning a line / carriage match.

+4


source







All Articles