My project folder structure is as below (Selenium +testng)
Proj
--Data folder
---General.properties
--src folder
---libraby package
----library.java
--testcases package
---testcase1 (testng test, extending library)
Problem: Null pointer when reading general properties file in library.java, but same code works fine when placed inside #test method in testcase. Whys is this happening? i want to read the properties inside library only, what should i do? please help.
public class Library{
public static Properties Prop = null;
public static FileInputStream sFileIn = null;
public static final String sProjpath = System.getProperty("user.dir").toString();
public void Initialization () throws Throwable
{
sFileIn = new FileInputStream(sProjpath+"\\Data\\General.properties");
Prop.load(sFileIn);}
The null pointer exception is because the public static Properties Prop = null; makes it null
To overcome this public static Properties Prop = new Properties(); is to be used
May be your are initializing the Prop object somewhere in your test case, so it works fine
Related
In my program, I access files in a relative way many times in different classes.
And I do not want to create a private static final String PATH variable every time.
File file = new File(PATH);
How can I make all the paths to a separate file in java (in which I will indicate all the relative paths) so that I can access it from anywhere in the program.
You can try making an Enum and put all the paths in it.
something like
public enum Paths{
FILE1("path_to_file"),
FILE2("path_to_file")
}
Create a separate class Util.java and add all static variables as public inside that class.
For example
public class Util {
public static final String PATH_ONE = "C:\\location\\filepath1";
public static final String PATH_TWO = "C:\\location\\filepath2";
}
Access these paths from any classes like this
File file = new File(Util.PATH_ONE);
I solved my problem with a small method:
public static String getValue(String key) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\main\\resources\\app.properties"));
return properties.getProperty(key);
}
I have 2 Class files. Class_login.java and Class_Company.java.
I have an xpath stored in different location in a properties file.
A method is written in Class_login.java to load this properties file.
static Properties objprop1 = new Properties();
public static FileInputStream fileInputS = null;
static void propManager() throws IOException {
fileInputS = new FileInputStream("C:\\Test-Automation\\FinanceSys\\myproj\\src\\test\\resources\\xpath.properties");
objprop1.load(fileInputS);
}
objprop1 is declared outside the method in Class_login.java.
I need to load this file again in Class_Company.java. If I use it like Class_login.PropertyManager(); and use same objprop1 the file does not load and the xpaths are not found.
Hence I created same method with a different name(static void PropertyManager() {) and public static Properties objprop = new Properties(); I know this is not the correct way. But how can this be done otherwise?
In the main method of Class_Company.java I called these methods separately so that I do not get a null xpath error as earlier.
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Class_login LogFeature = new Login();
Class_Company CC = new CCompany();
**Class_Company.PropertyManager();**
LogFeature.OpenBrowser("CH32");
LogFeature.EnterURL("http://localhost:90/AppFin");
LogFeature.PageMaximise();
LogFeature.EnterUserName("uname");
LogFeature.EnterPassword("abcd!#");
LogFeature.ClickLoginButton();
Thread.sleep(2000);
**Class_Company.propManager();**
CC.clickNewCompany("Manage");
Please tell me the right way of doing it. I want to use objprop in both the class files and only once in Class_Company.java. and not twice as highlighted above.
This is the basic example, which you need:
Global Variable declaration:
Class variableCollection {
public static string data;
}
You can use this variables by extending class Or object references.
class login extends variableCollection{
}
OR
class login{
variableCollection objvar = new variableCollection();
objvar.data = "";
}
You can use this same variable in multiple classes, same way.
In the unit tests as a side effect I am creating screenshots for various parts of the GUI.
I want to use these screenshots when compiling the documentation.
Therefore I want to save them to a directory within the source tree.
Is there any reliable way to get the source directory root when running a junit test?
If not, how can I make sure that unit tests run with cwd=project root when using eclipse, and when using maven?
wether you execute tests on eclipse or using maven, if you don't specify a path when you create the file it's automatically created at project root directory.
so if you specify a relative folder your files will go there :
public class TestFileCreation {
#Test
public void testFileCreation() throws IOException {
File f = new File("src/main/resources/hello.txt");
OutputStream ostream = new FileOutputStream(f);
String data = "Hello there !";
ostream.write(data.getBytes());
ostream.close();
}
}
will create a file inside the $PROJECT/src/main/resources.
Hope my answer helps
You can base on your classes location. Proposed solution here is to use class that will surely be in classpath. Then you can use class.getResource(""). Example
public class ResouceRoot {
public static String get() {
String s = ResouceRoot.class.getResource("").toString();
if (s.startsWith("jar:")) {
s = s.replace("jar:", "").replaceAll("!.*", "");
} else {
s = s.replaceAll("classes.*", "classes");
}
File f = new File(s.replace("file:", ""));
return f.getParentFile().getParentFile().getAbsolutePath();
}
public static void main(String[] args) throws IOException {
System.out.println(get());
}
}
(this code will give base dir for netbeans projects if they are launched from netbeans or by java -jar ... )
I am newbie to Java and facing below issue. I have following code:
public class ReadExcel {
Config conf = new Config();
String filePath = conf.getInputfilePath();
#Test
public void readFullXL() {
try {
FileInputStream FSRead = new FileInputStream(filePath);
I have declared this variable ‘filePath’ outside function because; I want to use it as global variable.
However, inside readFullXL(), I am not able to get value for variable ‘filePath’ and getting null pointer exception.
Can somebody suggest? How I can declare global variable in Junit file.
Edit:
Of course first you gotta check that your getInputfilePath() method does not return null.
Further: I suggest you go ahead and read some informations on UnitTesting (JUnit - Tutorial).
If it's just one test you could just instantiate your needed classes within that test.
#Test
public void readFullXL() {
Config conf = new Config();
FileInputStream FSRead = new FileInputStream(conf.getInputfilePath());
//...
}
If you have multiple tests relying on the same fixture you can go ahead and implement a setup method using the #Before annotation. The setup method will then be called before every test (#Test annotation) method.
class ReadExcel {
Config conf;
#Before
public void setUp() {
conf = new Config();
}
#Test
public void readFullXL() {
//...
FileInputStream FSRead = new FileInputStream(conf.getInputfilePath());
// Run your test
}
}
Thank you for your response and time.
I got it working by creating interface between config and ReadExcel file.
Also removed Junit test annotation from config file that was not required.
Thanks,
Ashvini
I was wondering if there is a better way to have a point to PATH in a properties file. Consider the following code:
public class Properties
{
//MIKE
public final static String PATH_TO_FILE_A = "C:\\programmer_MIKE\fileA.txt";
public final static String PATH_TO_FILE_B = "C:\\programmer_MIKE\fileB.txt";
//BILL
//public final static String PATH_TO_FILE_A = "/Users/BILL/Desktop/fileA.txt";
//public final static String PATH_TO_FILE_B = "/Users/BILL/Desktop/fileB.txt";
}
when any developer need to invoke FILE_A he simply does:
File file = new File(Properties.PATH_TO_FILE_A);
this works ok for BILL if he commented out MIKE's PATH_TO_FILE_A.
Q: is there a better design? If BILL committed his work including the Properties file - he will cause a problem to MIKE (no worries, he'll get a Coffee Latte later on).
the FILES are big (2-4Gb) and we don't want to put them in our repository (svn) and sometimes there are simply temporary folder to create a PDF so we don't want to put them in a "./docs" path.
Thanks for any pointer!
If for whatever reason you really must have hardcoded paths, then you could store them in some kind of map indexed by username. Something like:
public class Properties {
private static Map<String, DeveloperPaths> properties = create();
private static Map<String, DeveloperPaths> create() {
Map<String, DeveloperPaths> properties = new HashMap<String, DeveloperPaths>();
properties.put("mike", new DeveloperPaths(
"C:\\programmer_MIKE\fileA.txt",
"C:\\programmer_MIKE\fileB.txt")
);
properties.put("bill", new DeveloperPaths(
"/Users/BILL/Desktop/fileA.txt",
"/Users/BILL/Desktop/fileB.txt")
);
return properties;
}
public static File FileA()
{
String user = System.getProperty("user.name");
return properties.get(user).fileA;
}
public static File FileB()
{
String user = System.getProperty("user.name");
return properties.get(user).fileB;
}
}
class DeveloperPaths {
public File fileA;
public File fileB;
public DeveloperPaths(String pathA, String pathB) {
fileA = new File(pathA);
fileB = new File(pathB);
}
}
Then, the code to access each path would be identical regardless of developer, for example:
File myFile = Properties.fileA();
Normally paths are configurable entites and should be stored in property file.
Property files has a build in support in java and it uses Properties object for storing that information.
You can read the property file at startup or init (or similar) method of your application and read the proeprties from property file. This will make your configuration dynamic and anyone would be able to change it.
You can create a static method and call it on startup like:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class GetProperties {
public static Properties prop = new Properties();
public static void init() {
InputStream inputStream = GetProperties.class.getClassLoader().getResourceAsStream("application.properties");
try {
prop.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Things like this should be configured externally and/or passed in via parameter, system parameter, or environment variable. Alternatively you could use DI/IoC, but when there's no attached behavior, IMO a config value is plenty.
It's fine to have a hard-coded default, but otherwise stuff like this doesn't belong in code.