3

I am trying to run Junit test cases from command line.

I fire my tests in windows system from a folder D:\WorkSpace\Testspace\MyProject\target like this :

java -cp "classes;junit;dependency\*"  org.junit.runner.JUnitCore com.abc.TestA

This is a maven project. It throws the following error :

2019-07-09T17:59:41.330 ERROR [com.abc.IOUtil] - FileNotFoundException Occurredjava.io.FileNotFoundException: D:\WorkSpace\Testspace\MyProject\target\cde\FGH\SomeRandomFile.xml (The system cannot find the path specified)IOUtil

This cde folder containing the xmls is also inside the target folder from which I am firing my test commands.

Is there any way to include the resource files in java command line?

1 Answer 1

1

In your source code, use the following construct:

package com.foo.package;

public class Example {
    public void loadResourceExample) {
         Example.class.getResource("/cde/FGH/SomeRandomFile.xml");
         Example.class.getResource("relative/example.xml");
    }
}

The first line will load resource "/cde/FGH/SomeRandomFile.xml" from any folder or jar mentioned in the classpath, so in your example command line, D:\WorkSpace\Testspace\MyProject\target\classes\cde\FGH\SomeRandomFile.xml would for example be scanned.

The second line takes the package name of your class into account, so, it would for example check at D:\WorkSpace\Testspace\myProject\dependency\somedep.jar for entry /com/foo/package/relative/example.xml.

Note that the * syntax in the -cp parameter will take every JAR inside the stated folder and include it in the classpath. That's all it does.

If you are not using the getResource, you're dependent on the 'current working directory' which can be anything, really, and the -cp parameter wouldn't have any effect.

Sign up to request clarification or add additional context in comments.

2 Comments

So for reading the xml, I have to refactor the code and use getResource and there isn't any way to pass them as options from command line ?
If you want to pass the location of the XML file on the command line, you can do so of course. But then resource no longer factors into it; then you treat it as a plain jane file. Use java.nio.files.Path and Files API. Something like Files.readAllBytes(Paths.get(paramPassedByUser)). paramPassedByUser has to be a plain old file path; something like /Users/Tony/Documents/example.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.