everyone! I'm new in autotest and I meet the next problem using Tesng with Java: I have the next structure of my TestProject:
abstract public class BasePage {
public String str;
public BasePage(){
System.out.println("Constructor class: BasePage");
}
public void doSomething(){
System.out.println(str);
}
}
class PageOne:
public class PageOne extends BasePage{
public PageOne(String strP1){
this.str = strP1;
System.out.println("Constructor class: PageOne = " + this.toString());
}
}
class PageTwo:
public class PageTwo extends BasePage{
public PageTwo(String strP2){
this.str = strP2;
System.out.println("Constructor class: PageTwo = " + this.toString());
}
}
abstract public class BaseTest {
PageOne p1;
PageTwo p2;
@BeforeTest
public void setUp(){
System.out.println("BEFORE TEST in BaseTest: create p1 and p2");
p1 = new PageOne();
p2 = new PageTwo();
System.out.println("***** BEFORE *****");
}
class TestOne:
public class TestOne extends BaseTest{
public TestOne(){
System.out.println("Constructor class: TestOne");
}
@Test
public void testDoSomething(){
p1.doSomething();
p2.doSomething();
}
}
class TestTwo:
public class TestTwo extends BaseTest{
public TestTwo(){
System.out.println("Constructor class: TestTwo");
}
@Test
public void testDoSomething(){
p1.doSomething();
p2.doSomething();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="All Test Suite">
<test verbose="2" preserve-order="true" name="test1">
<classes>
<class name="org.example.tests.TestOne"/>
<class name="org.example.tests.TestTwo"/>
</classes>
</test>
</suite>
But when I started my testng.xml I got error:
java.lang.NullPointerException: Cannot invoke "org.example.pages.PageOne.doSomething()" because "this.p1" is null and my system.outs:
Constructor class: TestOne
Constructor class: TestTwo
BEFORE TEST in BaseTest: create p1 and p2
Constructor class: BasePage
Constructor class: PageOne = org.example.pages.PageOne@6a400542
Constructor class: BasePage
Constructor class: PageTwo = org.example.pages.PageTwo@7e0b85f9
***** BEFORE TEST END *****
strP1
strP2
***** AFTER CLASS *****
java.lang.NullPointerException: Cannot invoke "org.example.pages.PageOne.doSomething()" because "this.p1" is null
SO the second test TestTwo is failed because there are no more page variable p1. I can solve this problem by using annotation @BeforeClass or @BeforeMethod. But I can't understand why it doesn't work with @BeforeTest. Could anybody explain it, please!
The solution is to set variables static PageOne p1; PageTwo p2; I found detailed explanation here http://makeseleniumeasy.com/2020/08/09/are-you-getting-nullpointerexception-for-second-testng-test-while-running-as-a-suite/