How to get JBOSS Property Value in JUnit Test

1.2k views Asked by At
 public static Properties getInstance(String file)
 {
   String path = System.getProperty("jboss.server.base.dir") + File.separator + "configuration" + File.separator + "nxt" + File.separator + file;
   logger.info("path " + path);
   InputStream in = null;

   Properties prop = new Properties();
   try
   {
     in = new FileInputStream(path);
     prop.load(in);
   }
   catch (Exception e)
   {
   }
   finally
   {
     if (in != null)
     {
       try
       {
         in.close();
         in = null;
       }
       catch (IOException e)
       {
       }
     }
   }
   return prop;
 }

Code used to read from a property file in a specified location in the JBoss server

@Test
public void getEdgeHealthDignosticValidTest() throws Exception{
  String propertyVal = UtilProperty.getInstance("errorcodes.properties");
  assertTrue(propertyVal.contains("true"));
}

Above is the JUnit test to valid the method. Calling the method to get the property value from the properties file in the mentioned location. While running the JUnit test, getting NullPointerException. Since it can't get the System.getProperty("jboss.server.base.dir") value.

How can I get JBoss property in JUnit test.

2

There are 2 answers

1
Sasikumar Murugesan On

For JUnit you can directly read the property file

@Test
public void getEdgeHealthDignosticValidTest() throws Exception{
String propertyVal = UtilProperty.getInstance("errorcodes.properties");
assertTrue(getPropertyValueByProperty("some_property"));
}



private String getPropertyValueByProperty(String propertyName)
{
Properties prop = new Properties();
OutputStream output = null;

try {

    output = new FileOutputStream("config.properties");

    // get the properties value
    return prop.getProperty(propertyName);

} catch (IOException io) {
    io.printStackTrace();
} finally {
    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}
return null;
}
2
Stefan Birkner On

You have to set the property jboss.server.base.dir in your test.

@Test
public void getEdgeHealthDignosticValidTest() throws Exception {
  System.setProperty("jboss.server.base.dir", "/your/file");
  String propertyVal = UtilProperty.getInstance("errorcodes.properties");
  assertTrue(propertyVal.contains("true"));
}

You should reset the property after your test. An easy way to do this is by using System Rules' RestoreProperties rule.

@Rule
public final TestRule restoreSystemProperties
  = new RestoreSystemProperties();

@Test
public void getEdgeHealthDignosticValidTest() throws Exception {
  ...