Java代码触发java.lang.NullPointerException,请求协助排查根因
Looking at your stack trace and code, the NullPointerException is happening because the input stream returned by getResourceAsStream("application.properties") is null — meaning the JVM can't find your properties file when trying to load it. Let's break down the root cause and fix it step by step.
Root Cause
The exception points directly to line 22 in DriverInitializer.java:
properties.load(DriverInitializer.class.getClassLoader().getResourceAsStream("application.properties"));
ClassLoader.getResourceAsStream() returns null when the specified resource isn't found in the classpath. This is the direct cause of the NPE when Properties.load() tries to read from a null stream.
Step-by-Step Fixes
1. Verify the placement of application.properties
First, make sure your application.properties file is in the correct location so it's included in the classpath:
- For Maven/Gradle projects: Place the file in
src/test/resources(since your test classTc3_FogotPasswordis part of test code, it will prioritize resources from the test classpath). - For plain Java projects:
- Create a
resourcesfolder in your project root. - Move
application.propertiesinto this folder. - Right-click the project →
Build Path→Configure Build Path. - Under the
Sourcetab, add theresourcesfolder as a source directory.
- Create a
2. Correct the resource loading path (if needed)
If you placed the properties file in a subfolder (e.g., alongside your DriverInitializer class in the functions package), adjust the loading code to use a relative path with the class's own resource stream (instead of the classloader):
// If application.properties is in the same package as DriverInitializer properties.load(DriverInitializer.class.getResourceAsStream("application.properties")); // If it's in the root of the classpath, use a leading slash properties.load(DriverInitializer.class.getResourceAsStream("/application.properties"));
Using Class.getResourceAsStream() is often more reliable than the classloader version because it respects the class's package context.
3. Bonus: Fix potential follow-up issues
While not related to the current NPE, notice your chrome.path in the properties file is missing the .exe suffix (Windows requires this for executable files):
# Change from this: chrome.path=D:/Automation Files/Selenium Traning/Info_Project/drivers/chromedrivers # To this: chrome.path=D:/Automation Files/Selenium Traning/Info_Project/drivers/chromedriver.exe
This will prevent a NoSuchDriverException once you fix the NPE.
Verify the Fix
After adjusting the file location or loading code, re-run your test. The properties file should load successfully, and the NPE should be resolved.
内容的提问来源于stack exchange,提问作者lahimadhe

