我在测试套件中为失败的步骤截屏时遇到了空指针异常。我确实在谷歌上寻找解决方案,但还没有对我有用。如果有人能提供建议,请不胜感激。
我有 2 个安卓测试类和 2 个 iOS 测试类。android 和 iOS 都有自己的基本程序来初始化 android/iOS 驱动程序(声明为非静态)。测试类调用基程序来初始化驱动程序(如this.driver = .initiaze())以并行运行所有4个测试类。
我有 2 个单独的侦听器(在失败时截取屏幕截图),一个用于 android,一个用于 iOS。当任何测试失败时,侦听器程序调用(android侦听器调用android base,ios调用ios基本程序)基本程序getscreenshot方法,然后失败并显示NPE错误。
下面是 ref 的一些代码示例。
(注意 - 如果我在基本程序中将驱动程序定义为公共静态,则 NPE 错误消失,但并行运行失败并出现随机错误,因为一个类的驱动程序被另一个类使用)
Android base:(类似于 iOS Base 的代码,返回类型为 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"));
}
}
安卓测试类#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监听器:(类似于iOS监听器只创建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();
}
问题出在您的测试代码上。
按功能测试NG仅对每个<test>
标签调用一次@BeforeTest
。因此,如果在<test>
标签中有多个测试类尝试使用 Web 驱动程序实例,并且如果该 Web 驱动程序实例通过@BeforeTest
方法初始化,则对于第二个实例,Web 驱动程序实例将为 null。
要解决此问题,请将@BeforeTest
注释替换为@BeforeClass
注释。