Wednesday, 8 April 2020

Junit: Read resource file from src/test/resources

Below snippet is used to read a file from src/test/resources folder.

public File getResourceFile(String fileName) {
         ClassLoader classLoader = getClass().getClassLoader();
         return new File(classLoader.getResource(fileName).getFile());
}

For example, create config.properties file under src/test/resources folder.

config.properties
appVersion=1.23
appName=Chat Server

TestClass.java

package com.sample.app.utils;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.junit.Test;

public class TestClass {

 public File getResourceFile(String fileName) {
  ClassLoader classLoader = getClass().getClassLoader();
  return new File(classLoader.getResource(fileName).getFile());
 }

 @Test
 public void test1() throws IOException {
  File file = getResourceFile("config.properties");

  FileInputStream fin = new FileInputStream(file);

  Properties properties = new Properties();
  properties.load(fin);

  String version = properties.getProperty("appVersion");
  String applicationName = properties.getProperty("appName");

  assertEquals("1.23", version);
  assertEquals("Chat Server", applicationName);
 }
}





Previous                                                    Next                                                    Home

No comments:

Post a Comment