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

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?

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.

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.

Related

JUnit 5 test case for code that write files to file system. (Files.write)

I am fairly new with Junit and I need to write JUnit 5 test case for a method which has code statement:
public void method() {
// some code
Files.write(filepath)
// some more code
}
Will this code create new files every time when unit test is run ?
Is there a way to write a unit test for this scenario where files are not being created, or get deleted automatically once the test method execution is complete ?
Solution needs to be JUnit 5 compatible.
I have used JUnit 5's Temporary Directory(#TempDir) functionality to create a temporary directory and then pass the directory path to Files.write() method (along with the file name of course). The #TempDir will delete the files and temporary folder, it created, once the test execution is done. This way, I was able to execute the test case.

Java - having to test many inputs manually

I am using eclipse and need to test many files for my application. This mean, I have to go to: `run -> run configurations -> arguments', change them and re-run, for about 30 different test files.
Is there a quicker way to do this?
I have googled java automated testing. Just need some guidance, I am abit confused.
thanks
daniel
You should setup a Maven project or an ant build file to perform a suite of tests in one click rather than going one by one as you currently do.
Otherwise you can simply put all the tests you want to run in a specific package or folder then select : "Run all tests in the selected project, package or source folder" in the JUnit Run/debug configuration :
Another way with Eclipse is to create a test suite :
Open the New wizard
Select Java > JUnit > JUnit Test Suite and click Next.
Enter a name for your test suite class
Select the classes that should be included in the suite.
if it's just command line variations, you can sort it out adding a simple class like this (wrote this on the fly without a javac, may have errors)
public class PropertyRunner {
private static String commands [] = {"TEST_1", "TEST_2", "TEST_3" };
public static void main(String[] args) throws FileNotFoundException, IOException
{
Properties config = new Properties();
config.load(new FileInputStream("config.props"));
// config.props contains all my tests in the format:
// TEST_1=-a|-k|ccccc
// TEST_2=-b|-k|ccccd
// TEST_3=-c|-k|FEFEF
// now run test cases:
for (String key : commands) {
String cmdLine = config.getProperty(key);
// cmdLine is in format "-a|-b|ccccc"
String childArgs[] = cmdLine.split("\\|");
// Exec your main class passing args directly or via threads
// YourApp.main(childArgs);
}
System.exit(0);
}
}
It's pretty simple, you store all your command lines in a property file, and then iterate on every key executing your real main class and passing the arguments read from the property file.

Call .Java files, based on the test case name

Environemnt - Java + Junit +WebDriver
My requirement is this:
I have 120 XLS test cases, they are in xls.
(Example ->
1st test case -Discussion_DOcuOne.xls
2nd test case -Discussion_DOcuTwo.xls
etc...)
I have relevant Java files (one .java file for each xls test case).
(Example ->
1st test case -Discussion_DOcuOne.java
2nd test case -Discussion_DOcuTwo.java
etc...)
Through Java code, I am reading one by one xls test case.
And I need to call the related .Java file.
if testCaseName=Discussion_DOcuOne,then,
---- I need to call the Discussion_DOcuOne.java file
I have tried switch+case (by assigning numbers to all xls test cases).
But I need to write 120 case statements, which is not at all practical.
-----Here I stuck. I don't know how to RUN/CALL the specific Java file.
//For example the testCaseName is "Discussion_DOcuOne", I need to call/run the Discussion_DOcuOne.java.
I don't get any idea how to link these two.
Please find the example Java class (nothing but Java code for each manual test case, we call it TEST SCRIPT).
Every .Java file has one method runTestCase(), and I need to call that specific method which belongs to that specific test script.
---------------------- Here is the Discussion_DOcuOne.Java file---------------
public class Discussion_DOcuOne(){
String varOne="abc";
String varTwo="efg";
public void runTestCase(){
//do some thing using the variables above
}
}
just get name of test:
String fileName = "Discussion_DOcuOne";
then load class
Class clazz = Class.forName(fileName);
And create instance of Discussion_DOcuOne
clazz.newInstance();
then cast object to your interface and call your method

Make JAR as a standalone executable

Is there a way to convert JAR lib into JAR standalone?
I need to find a standalone java executable that convert PDF into TIFF and I've found these JARs: http://www.icefaces.org/JForum/posts/list/17504.page
Any ideas?
Easiest might be to create another Jar with a Main() entry point, and then just use the java.exe executable to run it:
e.g.
> java.exe -cp MyJarMain.jar;MyPDFJar.jar com.mydomain.MyMain myPDF.pdf
Where MyMain is a class with a Main static method.
You'll need something with a main entry point to pass in and interpret some command line arguments (myPDF.pdf in my made-up example)
You could do an assembly (are you using maven?) and make sure the Main-Class entry in the manifest.mf points to the main class.
Since there is no main-Method, you have to write one, or write a whole new class to call the class/method TiffConver.convertPDF .
The question is, how you're going to use it. From the command line, you need no executable jar. From the Gui, maybe you want to pass a file to be converted by drag and drop? Then you should take the parameter(s) passed to main as Input-PDF-Names (if they end in .pdf) and pass the names iteratively to TiffConverter, for "a.pdf b.pdf" =>
TiffConver.convertPDF ("a.pdf", "a.tiff");
TiffConver.convertPDF ("b.pdf", "b.tiff");
TiffCoverter will silently overwrite existing tiffs, so check that before or change the code there - this is clearly bad habit, and look out for more such things - I didn't.
/*
* Remove target file if exists
*/
File f = new File(tif);
if (f.exists()) {
f.delete();
}
Maybe you wan't to write a swing-wrapper, which let's you choose Files interactively to be converted. This would be a nice idee, if no filename is given.
If the user passes "a.pdf xy.tiff" you could rename the converted file to xy, as additional feature.
Without a main-class, however, a standalone jar would be magic.
However, building a native executale is almost always a bad idea. You loose portability, you don't profit from security- and performance improvements to the JVM or fixed bugs. For multiple programs you need always an independend bugfix, which you might have to manage yourself, if you don't have a package-management as most linux distros have.
after clearing some questions:
public static void main (String [] args) {
if (args.length == 1 && args[0].endsWith (".pdf")) {
String target = args[0].replaceAll (".pdf$", ".tif");
convertPDF (args[0], target);
}
}
This method you put into TiffConvert. It will allow you to convert a simple pdf-File, and generate a tif-File with the same basename but ending in .tif, silently overwriting an existing one of the same name.
I guess you now need to know how to start it?

Unit test with files system dependency - hidden files

I am writing a "Total Commander" like application in Java. There is quite obvious file system dependency here.
I want to unit test it. I created directory structure for test purposes, I keep it in known location in SVN repository. It works great so far.
Now, I have a method that should ignore hidden files. How can I go about this? Can I mark file hidden in the SVN somehow?
Other solution would be to make one of the files hidden in the build script before running tests, but I'm afraid this would mark file as modified and always show in a commit dialog.
Any suggestions?
I would put all the initialization of a test directory into the tests themselves. And such a case would be simple:
create a directory
put some hidden and visible files into it
test
tear down by removing the directory
Essentially, accessing the file system is a big no-no when unit testing. For starters, these tests are slow(er) than your in-system tests, thus reducing the likelihood of you running your tests at a high frequency (such as with every compilation).
Much better if you use an adapter-pattern to abstract away the access to the file system. I'm a .NET developer so my example will be in C#, but I expect you to be able to translate it simply enough:
public class MyManager
{
private readonly IFileAdapter _fileAdapter;
public MyManager(IFileAdapter fileAdapter)
{
_fileAdapter = fileAdapter;
}
}
public interface IFileAdapter
{
public FileStream Open(string fileName);
public string ReadLine(FileStream fileStream);
// More methods...
}
public class FileAdapter : IFileAdapter
{
public FileStream Open(string fileName)
{
return System.Io.File.Open(fileName);
}
public string ReadLine(FileStream fileStream)
{
return File.Open(fileStream);
}
}
Now, as usual, you can mock the file system, as you would any other class, supplying the returned results. Remember - you are not testing Java's IO classes it is assumed that they work. You are only testing your classes (i.e. MyManager, in the example above).
Leave the tests that actually use the file system to your integration / acceptance tests.
Hope this helps,
Assaf.
I would prefer to abstract file system, so that my unit-test wouldn't require access to real file system. Of course, this abstraction layer must be tested with real file system, but this allow you to reduce dependency on it.
As for storing hidden files in SVN, I second artemb. You should create all files necessary to test in JUnit set up. Presumably, you should prefer setup per test method (#Before and #After). But if you encounter test slowness problems, have a look at #BeforeClass and #AfterClass. I consider they can be used with test suites too.
artemb's answer is correct, you can use #Before and #After to create and remove your structure for each test.
Here is some code I use to create a new directory with some files in it, it will create the directory in the systems temp dir, this is important because depending on the machine your tests will run on, you may will not be allowed to create files or dirs somewhere else. (I had to write this code to allow my tests to be executed on our linux integration machine...)
final String tempdir = System.getProperty("java.io.tmpdir");
final String dirname = Long.toHexString(System.currentTimeMillis());
final File dir = new File(tempdir, dirname);
dir.deleteOnExit();
dir.mkdir();
final String path = dir.getAbsolutePath();
assertTrue(dir.exists());
// pre condition, the directory is empty
assertTrue(dir.list().length == 0);
// create temp files in the directory
final int nbFiles = 3;
for (int i = 0; i < nbFiles; i++) {
(File.createTempFile("test", ".txt", dir)).deleteOnExit();
}
BTW you will have to know on what platform you run to be able to create hiden files...

Categories

Resources