黄瓜弹簧和类配置

时间:2016-02-04 22:42:21

标签: spring cucumber-jvm

我正在努力使用Cucumber和Spring配置。 我正在使用PageFatty来编写selenium框架,使用BrowserFactory。

当我使用@ComponentScan,@ Component和@Autowire注释时,一切正常,但是当我想在@Configuration类中使用@Bean注释(BrowserFactory注册少量浏览器驱动程序)创建更复杂的bean时,它不起作用,在调试期间,我正在尝试自动装配的每一个变量都得到空值。

我正在使用Spring 4.2.4,版本1.2.4中的所有黄瓜依赖项。

配置:

@Configuration
public class AppConfig {

@Bean
@Scope("cucumber-glue")
public BrowserFactory browserFactory() {
  BrowserFactory browserFactory = new BrowserFactory();
  browserFactory.registerBrowser(new ChromeBrowser());
  browserFactory.registerBrowser(new FirefoxBrowser());
  return browserFactory;
}

@Bean(name = "loginPage")
@Scope("cucumber-glue")
public LoginPage loginPage() throws Exception {
  return new LoginPage();
}

@Bean(name = "login")
@Scope("cucumber-glue")
public Login login() {
  return new Login();
}
}

POP:

public class LoginPage extends Page {

  public LoginPage() throws Exception {
   super();
  }
  ...
}

页:

public class Page {

  @Autowired
  private BrowserFactory browserFactory;

  public Page() throws Exception{
    ...
  }
}

登录:

public class Login {

  @Autowired
  private LoginPage loginPage;

  public Login(){}
    ...
}

步骤:

@ContextConfiguration(classes = {AppConfig.class})
public class LoginSteps {

  @Autowired
  Login login;

  public LoginSteps(){
  }

  @Given("^an? (admin|user) logs in$")
  public void adminLogsIn(Login.User user) throws Exception {
    World.currentScenario().write("Logging in as " + user + "\n");
    login.as(user);
  }
}

错误:

cucumber.runtime.CucumberException: Error creating bean with name 'LoginSteps': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: Login LoginSteps.login; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'login': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private LoginPage Login.loginPage; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginPage' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [LoginPage]: Factory method 'loginPage' threw exception; nested exception is java.lang.NullPointerException

现在为了有趣的部分...... World类中的BrowserFactory正确自动装配!!

世界:

public class World {

  @Autowired
  private BrowserFactory browserFactory;
  ...
}

1 个答案:

答案 0 :(得分:1)

所以我会回答我自己的问题:)

问题是我在Page构造函数中调用了BrowserFactory。 看起来这个bean还没有创建并导致NPE。

为了解决这个问题:

  • 在配置中添加了@Lazy注释(使用此配置的所有元素,在该类中定义,以及Scan将找到的那些元素将创建为Lazy)
  • 将对Browser Factory的调用移至@PostConstruct方法

增加Spring配置的可读性还有两件事:

  • 将@ComponentScan添加到配置
  • 没有构造函数参数的类使用@Component和@Scope(" cucumber-glue")注释进行注释,因此可以从AppConfig.class中删除bean创建