如何在JUnit Test中获取JBOSS属性值

问题描述 投票:0回答:2
 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;
 }

用于从JBoss服务器中指定位置的属性文件读取的代码

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

以上是有效方法的JUnit测试。调用方法从上述位置的属性文件中获取属性值。在运行JUnit测试时,获取NullPointerException。因为它无法获得System.getProperty("jboss.server.base.dir")值。

如何在JUnit测试中获取JBoss属性。

java junit jboss jboss6.x
2个回答
0
投票

对于JUnit,您可以直接读取属性文件

@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;
}

0
投票

您必须在测试中设置属性jboss.server.base.dir

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

您应该在测试后重置该属性。一种简单的方法是使用System Rules' RestoreProperties规则。

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

@Test
public void getEdgeHealthDignosticValidTest() throws Exception {
  ...
© www.soinside.com 2019 - 2024. All rights reserved.