【问题标题】:Null Pointer Error Due To Initializing Spring Java Based Direct Injection由于初始化基于 Spring Java 的直接注入导致的空指针错误
【发布时间】:2024-05-22 23:05:02
【问题描述】:

我知道空指针错误是因为注入没有正确初始化。不完全确定如何修复它。

我有三个文件:main (CommonElements.java)、Constructor.java(bean)和 Driver.java(主要代码所在的位置)。

试图将driver.java注入commomelements,当它运行时,就会发生空指针异常。

这是每个的代码。任何帮助将不胜感激。

CommonElements.java

package PageFactory;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class CommonElements {

private Driver web;

    ApplicationContext ctx = new AnnotationConfigApplicationContext(Constructor.class);      
    Driver page = ctx.getBean(Driver.class); 

    @Test
    public void Common(final Driver web)
    {
        this.web = web;
        web.setup();
    }
}

Constructor.java

package PageFactory;

import org.springframework.context.annotation.*;

//constructor 
@Configuration //using java dependency injection
public class Constructor {
    @Bean
    public Driver driver() {
        return new Driver();
    }

}

驱动程序.java

package PageFactory;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Driver {

    private String baseUrl;

    public void setup() {
        final WebDriver driver;
        System.setProperty("webdriver.chrome.driver", 
        "drivers/chromedriver.exe"); //location of driver
        ChromeOptions options = new ChromeOptions(); 
        driver = new ChromeDriver(options);
        baseUrl = "https://www.google.com";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

}

【问题讨论】:

  • 你能发布堆栈跟踪吗?另外,你有没有使用调试器单步调试你的代码?
  • 它甚至不会运行调试器。这就是它所说的:启动 CommentElemetns 遇到问题:在“启动 CommonElements (1)”期间发生内部错误。 java.lang.NullPointerException

标签: java spring selenium-webdriver nullpointerexception initialization


【解决方案1】:

编辑:我不确定 junit 是否能够在您的测试方法中注入 Driver bean,您可以尝试这样的方法

package PageFactory;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class CommonElements {

private Driver web;

    ApplicationContext ctx = new AnnotationConfigApplicationContext(Constructor.class);      
    Driver page = ctx.getBean(Driver.class); 

    @Test
    public void Common()
    {
        page.setup();
    }
}

由于您手动初始化弹簧上下文,您可能不需要我在下面建议的内容

旧答案:

如果你想让junit初始化spring,我认为你需要在测试类中添加这个注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // i'm not 100% sure this one is needed 
public class CommonElements {
 ...
}

参考:link

【讨论】:

  • 嗯,这似乎也不起作用,感谢您的帮助!
  • 啊...我没有 getDriver() 或 setDriver() 方法。这可能会有所帮助...
  • mh 我注意到你以某种方式试图让 junit 在测试方法中注入你的 bean,我从未见过这样使用它,我会尝试删除驱动程序参数并执行 page.setup () 在您的测试中,我正在编辑答案以显示代码