How to write junit test case for method have args parameter - java

Here is my code for junit test case
public class HelptextValidation {
#Test
public void test() {
CLIReaderTest cli=new CLIReaderTest();
String Output="Test Execution";
assertEquals(cli.readCommandLineParameters(new String[]{"-h"}) , Output);
}
}
And is the class method for which test case is prepared
public class CLIReaderTest {
private String user = "";
private String password = "";
private String serverUrl = "";
private boolean spit_everythingtoLog = false;
public boolean readCommandLineParameters(String[] args) {
Logger log = Logger.getLogger(CLIReader.class);
Options options = new Options();
Option helpOpt = Option.builder("h").longOpt("help").desc("Usage Help").build();
options.addOption(helpOpt);
Option serverurl = Option.builder("url").longOpt("server url").desc("Server url").required().hasArg().argName("url").build();
options.addOption(serverurl);
Option userOpt = Option.builder("u").longOpt("user").desc("User Name").hasArg().argName("user").required().build();
options.addOption(userOpt);
Option pwdOpt = Option.builder("p").longOpt("password").desc("user password").hasArg().argName("password").required().build();
options.addOption(pwdOpt);
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args, true);
if(cmd.hasOption("v")) {
spit_everythingtoLog = true;
}
serverUrl = cmd.getOptionValue("url");
user = cmd.getOptionValue("u");
password = cmd.getOptionValue("p");
streamName = cmd.getOptionValue("s");
compList = cmd.getOptionValue("c");
}
catch (Exception e) {
String temp1="--help";
String temp2="[--help]";
String temp3="[-h]";
String temp4="-h";
if(temp1.equals(args[0]) || temp2.equals(args[0]))
{
System.out.println("Test Execution");
System.exit(1);
}
}
Here when user passes java -jar abc.jar -h in command line the output is "Test Execution"
The same i want to do with my test case but i am unable to pass the cmd argument and compare it with string. Can anyone please help me out in this?

Related

Using flag in java and calling it from one class to another class

I am using flag in one class
private boolean spit_everythingtoLog = false;
public boolean readCommandLineParameters(String[] args) {
Logger log = Logger.getLogger(CLIReader.class);
Options options = new Options();
Option helpOpt = Option.builder("h").longOpt("help").desc("Usage Help").build();
options.addOption(helpOpt);
Option serverurl = Option.builder("url").longOpt("server url").desc("Server url").required().hasArg().argName("url").build();
options.addOption(serverurl);
Option userOpt = Option.builder("u").longOpt("user").desc(" User Name").hasArg().argName("user").required().build();
options.addOption(userOpt);
Option pwdOpt = Option.builder("p").longOpt("password").desc(" user password").hasArg().argName("password").required().build();
options.addOption(pwdOpt);
Option completeLoggerOpt = Option.builder("v").longOpt("completeLogger").desc("Complete Logger Info + Errors").hasArg().argName("Optional").build();
options.addOption(completeLoggerOpt);
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args, true);
if(cmd.hasOption("v")){
spit_everythingtoLog = true;
}
serverUrl = cmd.getOptionValue("url");
user = cmd.getOptionValue("u");
password = cmd.getOptionValue("p");
streamName = cmd.getOptionValue("s");
compList = cmd.getOptionValue("c");
}
catch (Exception e) {
}
}
else
{
log.info(e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AutoLockComponent ", options, true);
}
}
return false;
}
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public String getServerUrl() {
return serverUrl;
}
public boolean getFlag() {
return spit_everythingtoLog;
}
Now how to call that flag value in another class such as
if(isLocked)
{
if(isLockedByMe)
{
//System.out.println("Do Nothing");
if(cli.getFlag()==true)
{
log.info("Yes");
}
else
{
log.info("No");
}
like i want that if user passes this arguement
-u stack -p flow -url https://www.google.com -v then print "Yes"
and if user passes this arguement
-u stack -p flow -url https://www.google.com then print "No"
Can anyone please help me out in this?

How to write a Junit test for a method that takes a file path and creates a new file?

I have method in Java class that takes a file path and creates a new file. How do I write a Junit test for this method?
public String sendToECM(String filePath) {
String ecmDocId = StringUtils.EMPTY;
try {
File file = new File(filePath);
if(file.exists()) {
DocumentPropertiesVO documentPropertiesVO = UploadFileToContentManagement.uploadDocument(file);
ecmDocId = documentPropertiesVO.getDocumentID();
}
return ecmDocId;
} catch (SomeException cee) {
log.error("There was an error adding the document", cee);
}
}
#Test
void testValidFilePath() {
String filePath = "path.txt";
String str = sendToECM(filePath);
Assertions.assertNotEquals(str, ""); // or null, depending on what your StringUtils.EMPTY is doing
#Test
void testInvalidFilePath() {
String filePath = "invalidPath.txt";
String str = sendtoECM(filePath);
Assertions.assertEquals(str, StringUtils.EMPTY);

Receiving null output for tdd url test

When I run junit tests on my project I receive the following error when trying to test that my project can build a url correctly. I am not sure what I am doing wrong below is the trace of the failed test run as well as the distancematrixconnection class and test class. It is producing a blank output when trying to compile the url string.
org.junit.ComparisonFailure: expected:<[http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial]> but was:<[]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at edu.bsu.cs222.gascalculator.tests.GoogleUrlTests.testAlbanyNYtoAlbanyINURL(GoogleUrlTests.java:26)
public class GoogleDistanceMatrixConnection
{
String startLocation;
String endLocation;
final String urlString = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + startLocation +"&destinations=" + endLocation +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
private static String XMLFile;
public String makeXMLFile(String start, String end) throws IOException
{
startLocation = start;
endLocation = end;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader( new InputStreamReader(
connection.getInputStream()));
for(String line = reader.readLine(); line != null; line =
reader.readLine())
{
setXMLFile(line);
}
return getXMLFile();
}
// public static void main(String[] args) throws IOException{
// GoogleDistanceMatrixConnection c = new GoogleDistanceMatrixConnection();
// }
public static String getXMLFile() {
return XMLFile;
}
public static void setXMLFile(String xMLFile) {
XMLFile = xMLFile;
}
public boolean doesPageExist() {
if(XMLFile == null)
return true;
else
return false;
}
}
public class GoogleUrlTests {
private GoogleDistanceMatrixConnection urlString = new GoogleDistanceMatrixConnection();
private String generatedUrl = "";
private String actualUrl = "";
#Test
public void testAlbanyNYtoAlbanyINURL() throws IOException {
generatedUrl = urlString.makeXMLFile("albany", "albany+in");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
#Test
public void testLosAngelesToNewYorkURL() throws IOException {
generatedUrl = urlString.makeXMLFile("losangeles", "newyork");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=losangeles&destinations=newyork&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
}
Comparing your test cases and your code in makeXMLFile, I'm confused of what you are really trying to do here.
If you want to pass you tests, then I think this code will do that for you. You can use URLEncoder to properly encode your URL string.
public class GoogleDistanceMatrixConnection
{
public String makeXMLFile(String start, String end) throws IOException
{
return "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(start) +"&destinations=" + URLEncoder.encode(end) +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
}
}
Otherwise, you need to clarify your question.

not able to retrieve command line options

I have been trying to put my head around this. There are no errors but I am not seeing the desired answer:
public class Clopts {
private static Options options = null;
private static final String InputDir = "i";
private static final String OutputDir = "o";
private String input;
private CommandLine cmd = null;
static{
options = new Options();
options.addOption(InputDir, false, "Input Directory");
options.addOption(OutputDir, false, "Output Directory. " + OutputDir );
}
public static void main(String[] args) {
Clopts cliProg = new Clopts();
cliProg.loadArgs(args);
}
private void loadArgs(String[] args){
CommandLineParser parser = new PosixParser();
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Error parsing arguments");
e.printStackTrace();
System.exit(1);
}
if (cmd.hasOption(InputDir)){
input = cmd.getOptionValue(InputDir);
System.out.println(input); // This is always null :(
}
}
}
While I am passing the argument -i foo -o bar
But I am not seeing the foo or bar every time i see is null.
Also I want to println in the main module. How do i get the options from command line and then print out what the options are.
When you define your options with:
options.addOption(InputDir, false, "Input Directory");
options.addOption(OutputDir, false, "Output Directory. " + OutputDir );
The false means they don't take arguments. If you want an option value you must specify true here.

RubyNoMethodError - call a ruby method from Java

I have this ruby class :
require 'stringio'
require 'hirb'
class Engine
def initialize()
#binding = Kernel.binding
end
def run(code)
# run something
stdout_id = $stdout.to_i
$stdout = StringIO.new
cmd = <<-EOF
$SAFE = 3
$stdout = StringIO.new
begin
#{code}
end
EOF
begin
result = Thread.new { Kernel.eval(cmd, #binding) }.value
rescue SecurityError
return "illegal"
rescue Exception => e
return e
ensure
output = get_stdout
$stdout = IO.new(stdout_id)
end
return output
end
private
def get_stdout
raise TypeError, "$stdout is a #{$stdout.class}" unless $stdout.is_a? StringIO
$stdout.rewind
$stdout.read
end
end
The "run" method should call an IRB's function and to capture the output (string format).
I want to call this function from a Java class but it can't find the IRB methods, even they are loaded (require 'hirb').
My java class looks like this :
public class MyClass {
private final static String jrubyhome = "/usr/lib/jruby/";
private String rubySources;
private String hirbSource;
private String myEngine;
private boolean loaded = false;
private void loadPaths() {
String userDir;
userDir = System.getProperty("user.dir");
rubySources = userDir + "/../ruby";
hirbSource = userDir + "/hirb.rb";
myEngine = rubySources + "/engine.rb";
System.setProperty("jruby.home", jrubyhome);
System.setProperty("org.jruby.embed.class.path", rubySources+":"+hirbSource);
System.setProperty("hbase.ruby.sources", rubySources+":"+hirbSource);
}
private String commandResponse(String command)
throws FileNotFoundException
{
String response;
loadPaths();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
ScriptingContainer container = new ScriptingContainer();
Reader reader = new FileReader(myEngine);
try {
Object receiver = engine.eval(reader);
String method = "run";
Object ob = container.callMethod(receiver,method,command);
response = ob.getClass().toString();
return response;
} catch (ScriptException e) {
System.out.println("exception");
}
return "FAILED";
}
public static void main(String args[])
throws IOException {
MyClass my = new MyClass();
System.out.println(my.commandResponse(args[0]));
}
}
Do you know what could be the problem?
[EDITED] After I extended the Kernel module and added the commands it worked.

Categories

Resources