Autowire在黄瓜Step Def测试中失败

时间:2018-11-28 06:12:02

标签: spring spring-boot

我有一系列黄瓜功能文件和当前项目中相关的步骤def测试列表

在def测试包中,我有这个Hook定义

@ContextConfiguration(classes = Application.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Hooks {
    ....
}

和RunCukesTest

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features", glue = { "com.myapp.test.jersey.rest.v1" })
@ContextConfiguration(classes = Application.class)
public class RunCukesTest {
    ....
}

以上类路径是正确的。 而且其中有一个步骤def测试

package com.myapp.test.jersey.rest.v1;

....
@ContextConfiguration(classes = Application.class)
public class OrderCreateServiceTest {
    ....
    @Autowired
    private OrderRepository repository;
}

但是我被Spring Boot跟踪错误

Exception in thread "main" java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?

然后,如果我像这样从step def类中取出@ContextConfiguration

//@ContextConfiguration(classes = Application.class)
public class CashpointCreateServiceTest {

显然,存储库对象的自动装配将因抛出NullPointerException

而失败

非常感谢任何人可以分享 (1)使用HookCukeTest的配置,如何在step def类中自动装配bean? (2)在@ContextConfigurationHook班级都拥有CukeTest可以吗?

1 个答案:

答案 0 :(得分:0)

您不需要RunCukesTest类上的ContextConfiguration。对于运行黄瓜测试,我使用以下设置。

Junit测试类启动黄瓜测试:

package mypackage.test;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test-integration/resources/features")
public class RunFeatures {

}

所有步骤定义类都扩展的基类。这样,所有步骤类都具有相同的spring注释。

package mypackage.test.steps;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.ContextConfiguration;

import mypackage.Application;

@ContextConfiguration(classes = { Application.class })
@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)
public class BaseSteps {

}

然后进行测试步骤

package mypackage.test.steps;

import mypackage.repo.SampleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import cucumber.api.java.en.When;

public class SampleSteps extends BaseSteps {

    @Autowired
    private SampleRepo sampleRepo;

    @When("^Sample repo is called$")
    public void no_words_are_saved() {
         sampleRepo.findAll("something");
    }

我不明白您的Hooks班是做什么的。我只在黄瓜jvm中使用带注释的钩子(例如@Before或@After)。如果您需要其他挂钩,是否可以进一步说明您要执行的操作?