TestNG无法实例化LoginPageTest类:InvocationTargetException与NPE问题
问题排查与解决办法
咱们先从异常栈找根源——你看到的TestNGException和InvocationTargetException都是表层问题,真正的罪魁祸首是java.lang.NullPointerException,而且是在加载Config.properties文件时触发的。
核心问题:错误使用System.getProperty()
看你的BaseClass构造方法里这行代码:
FileInputStream ip = new FileInputStream(System.getProperty("C:\\Users\\Jomonli\\workspace\\IVAPP_Automation\\src\\main\\java\\com\\IVAPP\\qa\\Config\\Config.properties"));
这里完全用错了System.getProperty()的用法!这个方法是用来读取系统环境变量或者JVM启动参数的(比如System.getProperty("user.dir")能拿到当前项目的根目录),你直接把文件路径当参数传进去,它肯定返回null,导致FileInputStream初始化失败,后面调用prop.load(ip)的时候自然就抛出空指针了。
针对性解决方案
方案1:直接使用文件路径(快速修复)
把那行错误的代码改成直接传入路径字符串,去掉多余的System.getProperty():
FileInputStream ip = new FileInputStream("C:\\Users\\Jomonli\\workspace\\IVAPP_Automation\\src\\main\\java\\com\\IVAPP\\qa\\Config\\Config.properties");
方案2:用相对路径+类加载器(推荐,避免硬编码)
硬写绝对路径的坏处是换电脑、换项目位置就失效,建议用maven项目的标准方式:
- 把
Config.properties文件移动到src/main/resources目录下(这是maven默认的资源文件目录,编译时会自动打包到classpath里)。 - 修改BaseClass的构造方法,用类加载器读取配置:
public BaseClass() throws IOException{ try{ prop = new Properties(); // 从classpath里加载配置文件 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Config.properties"); if(inputStream == null) { throw new FileNotFoundException("找不到Config.properties文件,请检查是否放在src/main/resources目录下"); } prop.load(inputStream); }catch(FileNotFoundException e){ e.printStackTrace(); throw e; // 主动抛出异常,让TestNG知道初始化失败 }catch(IOException e){ e.printStackTrace(); throw e; } }
如果不想移动文件,也可以用项目根目录的相对路径:
String projectRoot = System.getProperty("user.dir"); String configPath = projectRoot + "/src/main/java/com/IVAPP/qa/Config/Config.properties"; FileInputStream ip = new FileInputStream(configPath);
额外要清理的冗余代码
你的LoginPageTest的setUp()方法里有重复的IE驱动初始化代码,这些逻辑已经在BaseClass的intialization()里实现了,把setUp()里的这段代码删掉,避免冲突:
// String exePath = "C:\\Users\\Jomonli\\Desktop\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe"; // //For use of IE only; Please enable for IE Browser // System.setProperty("webdriver.ie.driver", exePath); // driver = new InternetExplorerDriver();
验证步骤
- 按照上面的方法修改BaseClass的配置加载代码。
- 如果用类加载器方案,确认Config.properties在
src/main/resources目录下。 - 执行Project > Clean清理项目,重新运行TestNG测试。
这样应该就能解决无法实例化LoginPageTest的问题了,因为空指针是导致后续一系列异常的根源。
内容的提问来源于stack exchange,提问作者Littin Jomon
相关产品推荐
相关产品推荐

