Accessing Test File in JUnit

I am trying access a test file from JUnit. I am able to read the test file if I put it into the same directory as the project file. However, I would like to read it from a directory in project directory. e.g.

- application
- build
- src
- application
- business
- test.java
FileInputStream("testdata.txt")
- testdata
- testdata.txt
OR
- testdata
- testdata.txt

5 comments

OK I figured it out myself. Under the menu option run/junit there is a place to enter the working directory.

0

Hi Vincent,
your test environment will be much more stable if it doesn't depend
on the current working dir.
Just use the classloader to open a stream:
this.getClass().getClassLoader().getResource("application/business/testdata/testdata.txt").openStream()
Be sure that all file extensions of you test files are on Idea's "Resource patterns" list
(settings, project, compiler), so that the files are copied to the output dir where they
can be found on the classpath (*.txt is included by default).


vincent hikida wrote:

I am trying access a test file from JUnit. I am able to read the test file if I put it into the same directory as the project file. However, I would like to read it from a directory in project directory. e.g.

- application
- build
- src
- application
- business
- test.java
FileInputStream("testdata.txt")
- testdata
- testdata.txt
OR
- testdata
- testdata.txt

0

Thanks Stephen that worked!
Right now for some reason our convention seems to be to keep only source under the source directory which is also classloader directory. Is there any way to access it from the following tree?

- application
-- build
-- src (classloader home)
--- application
-


business
-


test.java
-- testdata
--- testdata.xml

0

In fact that's a similar structure to the one we use here.
What I do is I just add the "testdata" folder as another source directory in Idea.
So the content root of the module would be "application" with "Source Folders"
"src" and "testdata".
See "File -> Settings -> Project -> Modules -> Paths".

vincent hikida wrote:

Thanks Stephen that worked!
Right now for some reason our convention seems to be to keep only source under the source directory which is also classloader directory. Is there any way to access it from the following tree?

- application
-- build
-- src (classloader home)
--- application
---- business
----- test.java
-- testdata
--- testdata.xml

0

Thanks again Stephen! It worked perfectly. The only other thing I needed to do was to add the directory to the junit classpath in my ant build.xml.

0

Please sign in to leave a comment.