0

I'm trying to write a Selenium java program that will take commands from an external source. e.g. I have externally wrote driver.findElement(By.id("username")).sendKeys("FirstName"); in a user friendly way so users can create selenium scripts without knowing the back end code.

Splitting it up into 4 sections:

1) identifier type e.g. id
2) identifier e.g. "username"
3) command type e.g. sendKeys
4) input data e.g. "Firstname"

In my code I am using a Runtime Compiler to compile String as code (I'm doing this as I can manipulate the entire code as string as it runs) this way I can have a small section of code to run anything referenced in the external source, so this code will work for sendKeys, click etc etc without needing any changes as long as the external source is created correctly.

I am able to run

 `"   String URL2 = \"id\";"  + "\n" +
        "   String URL3 = \"username\";"  + "\n" +
        "   String URL4 = \"sendKeys\";"  + "\n" +
        "   String URL5 = \"Grabhamn\";"  + "\n" +
        "   System.out.println(\"driver.findElement(By.\"+URL2+\"
  (\"+URL3+\")).\"+URL4+\"(\"+URL5+\");\");" + "\n" +`

This outputs driver.findElement(By.id(username)).sendKeys(Grabhamn); but my problem is then how do I execute this code in the runtime Compiler. Also, I need the code to output as
driver.findElement(By.id("username")).sendKeys("Grabhamn"); containing quotation marks in these places as I've been unsuccessful to do this also.

Any information on how to do this or alternative solutions will be much appreciated.

1 Answers1

0

I'm not sure whether I have correctly understood your question don't know and whether you have succeed with your task, as this was quite long ago. But for the future generations I will suggest a) using StringBuilder to create your code - this is recommended for large pieces of generated text; b) using chars to add "s

Thus, I'd try doing the following:

StringBuilder sb = new StringBuilder();
sb.append("driver.findByElement(By.");
sb.append(URL2);
sb.append('(');
sb.append('"');
sb.append(URL3);
sb.append('"');
...
System.out.plintln(sb.toString);

etc.

At best, I'd have a function

String parentheses(Object o){
    StringBuilder sb = new StringBuilder();
    sb.append('"');
    sb.append(o.toString());
    sb.append('"');
    return sb.tostring;
}

because this way you'll be sure that the parentheses are always closed.

Hope this may be of any help.

Kolya Ivankov
  • 129
  • 2
  • 11