ShridharBavannawar
ShridharBavannawar

Reputation: 174

How to get the file name from .properties file in java JUnit?

I have 8 test cases in which each test case makes use of a different file. How do I get the specific file from the .properties file which contains the path for the file(s). Some of the test cases are as shown below:

@Test
    public void testIfColDataReadIsCorrect() throws FileNotFoundException{

        obj.readExcelToGetData("D:/ExcelTestFiles/testExcelWithAllColData.xlsx");
        rowObj= obj.getRowRecord();
        assertEquals(rowObj.getName(), TEST_NAME);
        assertEquals(rowObj.getId(), TEST_id);
        assertEquals(rowObj.getDate(), TEST_DATE);
        assertEquals(rowObj.getMessage(), TEST_MSG);
        assertEquals(rowObj.getPage(), TEST_PAGE);
        assertEquals(rowObj.getType(), TEST_TYPE);
        assertEquals(rowObj.getLikeCount(),TEST_LIKECOUNT);
        assertEquals(rowObj.getShareCount(), TEST_SHARECOUNT);
        assertEquals(rowObj.getCommentCount(), TEST_COMMENTCOUNT);
    }
    @Test
    public void testWhenNameColDoesNotExists() throws FileNotFoundException{
        //FacebookDataExtraction obj= new FacebookDataExtraction();
        //FacebookFields rowObj=new FacebookFields();
        obj.readExcelToGetData("D:/ExcelTestFiles/testExcelWithNoNameCol.xlsx");
        rowObj= obj.getRowRecord();
        assertEquals(rowObj.getName(), null);
        assertEquals(rowObj.getId(), TEST_id);
        assertEquals(rowObj.getDate(), TEST_DATE);
        assertEquals(rowObj.getMessage(), TEST_MSG);
        assertEquals(rowObj.getPage(), TEST_PAGE);
        assertEquals(rowObj.getType(), TEST_TYPE);
        assertEquals(rowObj.getLikeCount(),TEST_LIKECOUNT);
        assertEquals(rowObj.getShareCount(), TEST_SHARECOUNT);
        assertEquals(rowObj.getCommentCount(), TEST_COMMENTCOUNT);

    }

I think this is not the best practice to directly input the file path to the method readExcelToGetData(). After going through certain posts I found that the files can the put in .properties file and can be read from it. How do I get the specific file path in each test case?

Upvotes: 0

Views: 1212

Answers (2)

Raoul Duke
Raoul Duke

Reputation: 455

You can load files from the classpath via a ClassLoader. E.g. : this.getClass().getClassLoader().getResourceAsStream("myFiles.properties"); So depending on your IDE, you might put the properties file into your source- or resources folder.

Upvotes: 2

Jiri Tousek
Jiri Tousek

Reputation: 12440

Running the JUnit test with @Parameterized runner allows you to run multiple iterations of the same test with different inputs.

You can read the test parameters from whatever source you wish and use them in the parameterized test without the need to copy the test method for every input.

You'll need at least JUnit 4.11 to use Parameterized.

Upvotes: 0

Related Questions