johnny-b-goode
johnny-b-goode

Reputation: 3893

How to check files in jUnit?

I need to cover some tests with JUnit. My method returns java.io.File. What are the attributes I need to check?

How do you write JUnit tests for methods, that operate with files? Is there any frameworks?

Upvotes: 0

Views: 6162

Answers (3)

maba
maba

Reputation: 48045

If you want to create some temporary files to run tests on then you should try the JUnit Rules with TemporaryFolder.

Here is an example.

That is a way to prepare your tests with necessary files.

But it all comes down to what you actually want to do and your question is not really giving many clues...

Upvotes: 2

Stephen C
Stephen C

Reputation: 718678

Method returns java.io.File. What is the best way to check it?

There is no "best way". It completely depends on what the file is supposed to contain, and what you NEED TO test.

In different situations I might test that:

  • the File argument is non-null,
  • the filepath encoded by the File has a given value,
  • the corresponding file exists,
  • the corresponding file has given length or line count,
  • the corresponding file contains a given string (or strings) or pattern (patterns),
  • the file contents exactly matches a file of expected output,
  • the file contents parses to the same data structure as another file, or
  • the file contents parses to some data structure that some other properties.

Upvotes: 3

Dewfy
Dewfy

Reputation: 23614

Every test must be based on requirement. For example it can be claimed that method returns name of non-existing file that can be safely created - unit test must check that really no such file:

assertTrue(!file.isDirectory() && !file.canRead())

When requirements tell you that File returned is file with some properties, you have to check exactly claimed properties. For example per requirements at position 3 you have discover symbol '@'. So your test should check:

  1. File really exists, can be read
  2. Poistion 3 really contains expected symbol

Upvotes: 1

Related Questions