jaypax123
jaypax123

Reputation: 218

Read file content from different package in JUnit

I am trying to read a file (which contains my data) in my JUnit code.

I have a source folder named "test" and under it are the two packages below

com.junit.codes (JUnit codes)

com.junit.codes.data (csv Files i.e. myData.csv)

My problem is I cant access the files under com.junit.codes.data.

I have tried using classLoader but it does not work.

Can anyone help me with this problem?

Upvotes: 1

Views: 702

Answers (1)

Zapodot
Zapodot

Reputation: 462

Presuming you are using a Maven based setup, do the following:

  1. As non-Java files by default is not copied to the "target" folder in the "compile" phase you should add your csv-file to src/test/resources/com/junit/codes/data
  2. From your test class you should now be able to do getClass().getResourceAsStream("./data/myData.csv") to open an input stream to read the data from.

Example:

package com.junit.codes;
import org.junit.Test;
import java.io.InputStream;
import static org.junit.Assert.assertNotNull;

public class ReadTest {
    @Test
    public void name() throws Exception {
        try(final InputStream inputStream = getClass().getResourceAsStream("./data/myData.csv")) {
            assertNotNull(inputStream);
        }
    }
}

Upvotes: 1

Related Questions