webdriver DataProvider TestNG - java

All
I have problems with my code in TestNG.
Need to Annotate Parameters to the method.
1) Generation Random Stings
public String RandomName(){
ArrayList<String> alphaNum = new ArrayList<String>();
for (char i = 'A';i<= 'Z';i++){
String s = new String();
s +=i;
alphaNum.add(s);
}
for (char i = 'a';i<= 'z';i++){
String s = new String();
s +=i;
alphaNum.add(s);
}
String[] RandomEnteredField = new String[10];
for (int i = 0; i < RandomEnteredField.length; i++) {
RandomEnteredField[i] = alphaNum.get((int)(Math.random()*alphaNum.size()));
}
String result = "";
for(int i = 0; i < RandomEnteredField.length; i++)
{
result += RandomEnteredField[i];
}
System.out.println(result);
return result;
}
2) In test class I save it like global String
#Test(priority =0)
public void CreateAcount() throws Exception {
objFifthIssue = new TheFifthIssue(driver);
objFifthIssue.ClickOnMyAccount();
String rn = objFifthIssue.RandomName(); // add new argument to EnterRegistrationForm and also 2 below
EmailRandom = objFifthIssue.RandomName();
Password = objFifthIssue.RandomName();
objFifthIssue.EnterRegistrationForm(rn,EmailRandom,Password);
objFifthIssue.VerifyRegistrationDone();
}
3) I would like saved EmailRandom and Password to set in another test class like parameters
#Test(priority =2, dataProvider="LogInOUt")
public void LogoutLogIN(String EmailRandom, String Password) throws Exception {
System.out.println(EmailRandom + Password);
objSixIssue = new SixIssue(driver);
objSixIssue.LogoutLogIN(EmailRandom,Password);
}
4) In DataProvider I try to
#DataProvider(name = "LogInOUt")
public static Object[][] Generation() {
return new Object[] { { EmailRandom }, { Password }};
}

You have an interesting return in your Dataprovider there:
public static Object[][] Generation() {
return new Object[] { { EmailRandom }, { Password }};
}
I assume what you're trying to do here is this:
public static Object[][] Generation() {
return new Object[][] { { EmailRandom }, { Password }};
}
Now it's actually returning the correct datatype. However, this is not the correct way to utilize Selenium DataProviders. (the above code won't work)
DataProviders, as you know, are two-dimensional arrays. This is how you're doing it:
Array 1: {argument 1}
Array 2: {argument 2}
This is how it's supposed to work:
Array 1: {argument 1, argument 2}
Array 2: {argument 1, argument 2}
The first dimension of the array iterates on each time it runs the method. It's two-dimensional so that you can run a different set of arguments with the same method over and over. Does that make sense?
Example: You want to run the method meet(Person, Person) three times. The first time you run it, you want Bob and John to meet. The second time, you want Laura and Sarah to meet. The third time, you want Bob and Sarah to meet. You would use this DataProvider on the meet() method:
public static Object[][] provider() {
return new Object[][] {
{Bob, John},
{Laura, Sarah},
{Bob, Sarah}
};
}
Get it?
So now, if we look at your code, it appears you're only trying to pass one set of arguments with the DataProvider. Since it has to be a two-dimensional array, though, we can just put all the arguments in the first array. Like so:
#DataProvider(name = "LogInOUt")
public static Object[][] Generation() {
return new Object[][] {{ EmailRandom, Password }};
}
Let me know if anything I said didn't make sense :)

Related

Java - List of Objects Changes Previous Elements

I am trying to create a list of objects from a database but whenever I add another element to the end of the list it changes the values of the previous elements. I have seen similar questions on here but none seem to help my problem.
Here is the code for the class Deck
public static class Deck {
private static int deckid;
private static String deckName;
private static int deckCreatorID;
private static boolean isDeckPublic;
private static String deckDescription;
public Deck(int id, String name, int creator, boolean isPublic, String description){
deckid = id;
deckName = name;
deckCreatorID = creator;
isDeckPublic = isPublic;
deckDescription = description;
}
public String getDeckName(){
return deckName;
}
public String getDeckDescription(){
return deckDescription;
}
public int getDeckCreator(){
return deckCreatorID;
}
public int getDeckid() { return deckid; }
public boolean getDeckPublic() { return isDeckPublic; }
}
Here is the code to create and add the objects to the list:
public static List<marketplaceController.Deck> getAllCards(){
List<marketplaceController.Deck> deckList = new ArrayList<>();
List<Integer> idList = new ArrayList<>();
List<String> nameList = new ArrayList<>();
List<Integer> cIdList = new ArrayList<>();
List<Boolean> publicList = new ArrayList<>();
List<String> descList = new ArrayList<>();
try{ // This try-catch block is mainly from https://www.javatpoint.com/example-to-connect-to-the-mysql-database
Class.forName("com.mysql.cj.jdbc.Driver"); // Define the driver to use
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/users","root","UnlockDB.123"); // Connect to the local db
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from decks"); // Execute the query on the db
while(rs.next()) { // Runs while columns are to be store
idList.add(rs.getInt(1));
nameList.add(rs.getString(2));
cIdList.add(rs.getInt(3));
publicList.add(rs.getBoolean(4));
descList.add(rs.getString(5));
}
con.close();
}
catch(Exception e){
loginController.popup("An error occurred connecting to the database", "An error occurred");
}
for(int i = 0; i < idList.size(); ++i){ // This loop outputs the correct data
deckList.add(new marketplaceController.Deck(idList.get(i), nameList.get(i), cIdList.get(i), publicList.get(i), descList.get(i)));
System.out.println(deckList.get(i).getDeckid());
System.out.println(deckList.get(i).getDeckName());
System.out.println(deckList.get(i).getDeckCreator());
System.out.println(deckList.get(i).getDeckPublic());
System.out.println(deckList.get(i).getDeckDescription());
}
for(int i = 0; i < deckList.size(); ++i){ // This outputs the overwitten data
System.out.println(deckList.get(i).getDeckid());
System.out.println(deckList.get(i).getDeckName());
System.out.println(deckList.get(i).getDeckCreator());
System.out.println(deckList.get(i).getDeckPublic());
System.out.println(deckList.get(i).getDeckDescription());
}
return deckList;
}
When the elements of deckList are printed straight after they are created they show the correct elements e.g.
1
TESTDECK
1
true
""
2
TESTDECK2
1
true
""
However, when I iterate through the completed list and print the contents the following is printed:
2
TESTDECK2
1
true
""
2
TESTDECK2
1
true
""
This is probably a very stupiud question but I'm reltively new to Java and so any help is greatly appreciated
As #jhamon pointed out using static variables can be a very bad idea when you don't know what this means. Simply put a static field is shared among all instances of a class because it is a property of the class and not the instance. So when you have 10 instances of Deck all of them will return the same value for e.g. deckid.

Command line arguments [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've created a class called Human that works properly, it takes 2 arguments, age and name, to create a human.
To create a Human with command line arguments, I want to write
java Filename -H "Anna" 25
And it should create a Human with thatname="Anna", and thatage=25, where 25 is an int.
The code I've written is creating a list called Argument, and iterating through it to find -H. I need to do this because I'm going to be using this to create different classes later. I just need help with the syntax on the lines where I've written thename=, and theage=, because I don't know how to get the next item in list, and next-next item in list.
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (String item2: Argument) {
if (item2 == "-H") {
thatname = Argument.get(item2+1)
thatage = Argument.get(item2+2)
Human person = new Human(thatname,thatage);
System.out.println(person);
}
Why not just loop the args?
for ( int i = 0; i < args.length; i++ ) }
if (args[i].equals("-H")) {
i++;
thatName = args[i];
i++;
thatAge = args[i];
}
}
You should add some code to catch if one does not follow the rules you have set. Probably not enough arguments or other things humans do at the keyboard...
thatname = Argument.get(Argument.indexOf(item2)+1);
thatage = Argument.get(Argument.indexOf(item2)+2);
OR you know that 1st element is -H, 2nd element is name and 3rd is age, so you can use below code directly
thatname = Argument.get(1);
thatage = Integer.parseInt(Argument.get(2));
Your code have some problems, let me explain them to you for your assistance.
You cannot compare Strings with == you have to use equals method
in the String to compare between two Strings.
You have to use this for loop for(int i = 0; i < Argument.size();
i++) syntax so that you can iterate from zero to the number of
items in the list.
get method in ArrayList take the index as parameter and return the value at that index.
You can add i += 2 to skip the next two iterations which will
return the name and age value of the human. (It is optional)
Here is the working code:
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
String currentItem;
for (int i = 0; i < Argument.size(); i++) { // it will iterate through all items
currentItem = Argument.get(i); // getting the value with index;
if (currentItem.equals("-H")) {
String thatname = Argument.get(i+1);
String thatage = Argument.get(i+2);
i += 2; // Skipping 2 iterations of for loop which have name and age human.
Human person = new Human(thatname,thatage);
System.out.println(person);
}
}
}
You cannot iterate the list using String. When iterating a list you required a index number like list.get(indexNumber);
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (int i=0;i<args.length;i++) {
if (args[i].trim().equals("-H")) {
i++;
thatname = Argument.get(i);
i++;
thatage = Argument.get(i);
Human person = new Human(thatname,thatage);
System.out.println(person.getName()+" "+person.getAge());
}
Why using array list when you can directly use args? and while you're having only two parameters don't use a for loop access them direclty.
One thing you should know is that String is an object in java so comparing two Strings with == sign will return false even if they have same value (== will compare the id of the object), you should use .equale() function to compare the value of the object.
Check out this code :
public static void main(String[] args) {
if(args.length>0)
{
try{
if (args[0].equals("-H")) {
Human person = new Human( args[1],args[2]);
System.out.println(person);
}
}catch(ArrayIndexOutOfBoundsException exception) {
System.out.println("error with parameters");
}
}else
System.out.println("No command");
}

What's wrong with this randomized string and if-statement in java

I'm wetting my feet in java, and I've stumbled upon an issue. I suspect there might be already an answer for it, but I'm too much of a novice to know what it is I should be looking for - it also means my terminology might not be correct.
In the following code, I'm trying to create a random choice from an array of words, then use an if-statement to either display or not display the word. The problem is, although the condition of the if-statement is met (either the string "cat" or the string "dog" are obtained), the action displays any of the listed words, instead of either "cat" or "dog"
I suspect that when I use System.out.println(exampleWord()); in line 10, the routine obtains a new value from the array, effectively ignoring the if-statement.
What's the easiest way around this?
import java.util.Random;
public class Phrasing {
String word;
public static void main(String[] args) {
int i = 1;
while (i < 9) {
if ("cat".equals(exampleWord()) || "dog".equals(exampleWord())) {
System.out.println(exampleWord());
i++;
}
}
}
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
int index = random.nextInt(listedWords.length);
Phrasing wordOutput;
wordOutput = new Phrasing();
wordOutput.word = listedWords[index];
return (wordOutput.word);
}
}
Yes, you are right. Each time you call exampleWord(), a random word is generated. Try storing it in a String once.
public static void main(String[] args) {
int i = 1;
while (i < 9) {
String s = exampleWord();
if ("cat".equals(s) || "dog".equals(s)) {
System.out.println(s);
i++;
}
}
}
Also, it seems like you are doing some work unnecessarily, in the exampleWord method. You could do
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
return listedWords[random.nextInt(listedWords.length)];
}
You should generate the word only once and then perform checks and output it:
while (i < 9) {
String exampleWord = exampleWord();
if ("cat".equals(exampleWord) || "dog".equals(exampleWord)){
System.out.println(exampleWord);
i++;
}
}
The problem is that you are executing exampleWord() every time you compare "cat" or "dog" to the result, and then again you execute it to print the result.
Just execute exampleWord() one time inside the loop, store it in a variable and finally compare and print the result.
Something like:
String result = exampleWord()
if("cat".equals(result) || "dog".equals(result)) {
System.out.println(result);
i++;
}

Value of Arraylist is unexpected

I have this method that adds temp to xy array.
public void printBoard(int temp[][],int type){
if(type == 1) {
xyArray.add(new Array(temp));
numberOfSolutionsXY++;
}
}
xyArray is global and declared as
public ArrayList<Array> xyArray = new ArrayList();
When I check its value before exiting the method printBoard, it prints the expected 2d array. But when I go to another method, the value of xyArray is different. It has the value of the other Arraylist.
I checked back and forth many times, I did not just mistype the parameter. It's not happening only on xyArray, the same happens to other arraylists: regArray, xArray and yArray
This is how I check the value
System.out.println("\n xy \n"+xyArray.toString());
I do solveBoard method and tries to add the expected value of arrays but different values were appended. They were all the same.
problemArray.add(new Array(board));
solveBoard(board,0,0,4);
if(numberOfSolutions>0)
solutionArray.add(new ArrayList(regularArray));
solveBoard(board,0,0,3);
if(numberOfSolutionsX>0)
solutionArray.add(new ArrayList(xArray));
if(dimension%2==1){
solveBoard(board,0,0,2);
if(numberOfSolutionsY>0)
solutionArray.add(new ArrayList(yArray));
solveBoard(board,0,0,1);
if(numberOfSolutionsXY>0)
solutionArray.add(new ArrayList(xyArray));
}
solutionsArray.add(new ArrayList(solutionArray));
System.out.println("\nsolutions\n"+regularArray.toString());
All of them have the value of problemArray. Even though i placed problemArray.add(new Array(board)); at the bottom, they still get its value.
This is the class Array i've made
public class Array {
int[][] array;
public Array(int[][] initialArray){
array = initialArray;
}
public String toString(){
String x = "";
for(int i = 0;i<array[0].length;i++){
for(int j = 0;j<array[0].length;j++)
x+=array[i][j];
x+="\n";
}
return x;
}
}
Full code here
Try to rename your "Array" class, for example to "MyArray"
And i suppose there are some troubles with Array class constructor.
Try to copy initialArray in to your local variable.
public class MyArray {
int[][] localArray;
public MyArray(int[][] initialArray) {
localArray = initialArray.clone();
for (int i = 0; i < initialArray.length; i++) {
localArray[i] = initialArray[i].clone();
}
}
public String toString() {
// ...
}
}

Return multiple arrays to the main method

My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.

Categories