当在我的测试套件中为失败的步骤截屏时,我被空指针异常卡住了。我做了谷歌寻找解决方案,但还没有为我工作。如果有人能给我建议,我将不胜感激。
我有2个android测试类和2个iOS测试类。android和iOS都有自己的基础程序来初始化android/iOS驱动程序(声明为非静态)。测试类调用基础程序来初始化驱动程序(如this.driver = .initiaze()),以便并行运行所有4个测试类。
我有两个独立的监听器(在失败时截图),一个用于安卓系统,另一个用于iOS。当任何测试失败时,监听器程序调用(android监听器调用android基础程序,ios调用ios基础程序)基础程序getscreenshot方法,然后该方法失败并显示NPE错误。
下面是ref的一些代码示例。
(注意-如果我在基础程序中将驱动程序定义为public static,那么NPE错误就会消失,但并行运行会失败,并出现随机错误,因为一个类的驱动程序会被其他类使用)
安卓基础:(类似于iOS基础的代码,返回类型为IOSDriver)
g_MobileBase.java:
public class g_MobileBase {
@SuppressWarnings("rawtypes")
public AndroidDriver driver=null;
public DesiredCapabilities cap;
@SuppressWarnings("rawtypes")
public AndroidDriver InitializeDriver() throws IOException
{//initialization code; return driver;
}
public void getScreenshot(String classname, String testname) throws IOException
{
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src,new File(System.getProperty("user.dir")+"\\ErrorSnapshots\\"+classname+"_"+testname+"_"+new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date())+".png"));
}
}安卓测试class#1:
public class G_SearchStore_LocOff extends g_MobileBase{
@BeforeTest (description="Initialize driver and install application")
public void Initialize() throws IOException
{
this.driver = InitializeDriver();
//remaining code
}
@AfterTest (description="Close application and Quit driver")
public void finish()
{
driver.closeApp();
driver.quit();
}
@Test
.................some methods
.................some methods
}Android Listener:(类似于iOS listener,只创建ios基础程序的对象)
public class g_testListener implements ITestListener{
g_MobileBase b = new g_MobileBase();
@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
String[] temp = result.getInstanceName().toString().split("\\.");
String classname = temp[1];
try {
b.getScreenshot(classname,result.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}发布于 2019-04-17 12:29:19
问题出在您的测试代码中。
TestNG by功能对于每个<test>标记只调用一次@BeforeTest。因此,如果您的<test>标记中有多个测试类正在尝试使用webdriver实例,并且如果该webdriver实例是通过@BeforeTest方法初始化的,那么对于第二个实例,webdriver实例将为空。
要解决此问题,请用@BeforeClass注释替换@BeforeTest注释。
https://stackoverflow.com/questions/55694145
复制相似问题