I just started to use TestNG and have a problem with tests. After populating the ArrayList I try to get the first element and after removing it(queue like), but all tests look like work parallel because each test gets the same element, I mean that the second test starts working before the first test remove the element from ArrayList.
Lab1Main inst = new Lab1Main();
ArrayList<String> assets;
/**
* Method for reading input from the console
* reads only 2 times
* @return ArrayList<String>
*/
private ArrayList<String> input() {
assets = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println("type your data and press enter at ther end");
String line = scan.nextLine();
assets.add(line);
int count = 0;
while (count < 1) {
line = scan.nextLine();
assets.add(line);
count++;
}
scan.close();
System.out.println("Scanner closed" + assets);
return assets;
}
/**
* Test will pass or fail depends on input data
* if input String length less than 3(str.length<3) test will fail
* because mutator(setStr) in class Lab1Main will throws an error and won't initialize the variable
*/
@Test
public void firstTest() {
try {
inst.setStr(assets.get(0));
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e);
} finally {
Assert.assertEquals(inst.getStr(), assets.get(0));
assets.remove(0);
}
}
@Test
public void secondtTest() {
try {
inst.setStr(assets.get(0));
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e);
} finally {
Assert.assertEquals(inst.getStr(), assets.get(0));
assets.remove(0);
}
}
@BeforeTest
public void beforeTest() {
assets = input();
}
@AfterTest
public void afterTest() {
}
}
Class for testing
private String str;
public Lab1Main() {
// TODO Auto-generated constructor stub
}
public String getStr() {
return str;
}
/**
* throws error if input string length<3
* @param str
* @throws StringIndexOutOfBoundsException
*/
public void setStr(String str) throws StringIndexOutOfBoundsException {
if (str.length() < 3) {
throw new StringIndexOutOfBoundsException(
"Input string has to has length > 2 your lenght is " + str.length());
} else {
this.str = str;
}
}
}
Thank you!