Как я могу это исправить при загрузке Spring Boot перед встроенной Cassandra при использовании Cucumber? - PullRequest
1 голос
/ 16 июня 2019

У меня возникли некоторые проблемы с использованием пружинно-кассандрового блока, пружинного башмака и пружинного огурца. Приведенная ниже конфигурация отлично работает для модульных тестов, но как только я добавляю spring-cucumber в микс и пытаюсь выполнить некоторые интеграционные тесты, оказывается, что он полностью игнорирует мой MyCustomOrderedTestExecutionListener и загружает пружинную загрузку перед cassandra, давая мне «NoHostFoundException».

Я действительно мог бы воспользоваться советом о том, как обеспечить загрузку встроенной кассандры. Любая помощь с благодарностью.

Следующая настройка:

@ActiveProfile("INTEGRATION_TEST")
@SpringBootTest
@EmbeddedCassandra(configuration = "cassandra.yaml")
@TestExecutionListeners(
  listeners = MyCustomOrderedTestExecutionListener.class,
  mergeMode = MERGE_WITH_DEFAULTS)
@CassandraDataSet(value = "cql/dataset1.cql", keyspace = "mykeyspace")
public class TestStepDef{

//omitted for brevity

} 

My Custom заказал слушателя выполнения теста:

public class MyCustomOrderedTestExecutionListener extends AbstractTestExecutionListener {

    @Override
    public void afterTestMethod(TestContext testContext) throws Exception {
       //omitted for brevity
    }

    @Override
    public int getOrder() {
        return  Ordered.HIGHEST_PRECEDENCE;
    }
}

Тестер огурцов:

@RunWith(Cucumber.class)
@CucumberOptions(features="resources/features", glue="resources/glue")
public class TestRunner {}

Edit:

Глядя на пружинную фабрику огуречной пружины, контекст приложения загружается еще до того, как будет выполнен класс передTestClass (beforeTestClass выполняется notifyContextManagerAboutTestClassStarted):

 public void start() {
        if (this.stepClassWithSpringContext != null) {
            this.testContextManager = new CucumberTestContextManager(this.stepClassWithSpringContext);  
        } else if (this.beanFactory == null) {
            this.beanFactory = this.createFallbackContext();
        }

        this.notifyContextManagerAboutTestClassStarted();
        if (this.beanFactory == null || this.isNewContextCreated()) {
            this.beanFactory = this.testContextManager.getBeanFactory();
            Iterator var1 = this.stepClasses.iterator();

            while(var1.hasNext()) {
                Class<?> stepClass = (Class)var1.next();
                this.registerStepClassBeanDefinition(this.beanFactory, stepClass);
            }
        }

        GlueCodeContext.INSTANCE.start();
    }

Пройдя глубже, мы видим, что контекст приложения загружен здесь:

class CucumberTestContextManager extends TestContextManager {
    public CucumberTestContextManager(Class<?> testClass) {
        super(testClass);
        this.registerGlueCodeScope(this.getContext());
    }

     private ConfigurableApplicationContext getContext() {
    return (ConfigurableApplicationContext)this.getTestContext().getApplicationContext();
     }
...

}

Какой-нибудь совет, как это обойти?

Ответы [ 3 ]

1 голос
/ 17 июня 2019

Вот как я это делаю:

IntegrationConfig:

class IntegrationConfiguration {
// your cassandra startup
}

ComponentTestSpecification

@ContextConfiguration(classes = Application.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Import(IntegrationConfiguration.class)
abstract class ComponentTestSpecification {
// reusable integration-test methods here
}

Тест (отличный, должен быть конвертируемым в jUnit / что угодно):

class AccessControllerSpec extends ComponentTestSpecification {
// test methods
}
1 голос
/ 16 июня 2019

В настоящее время огурец вызывает только TestContextManager.beforeClass и TestContextManager.afterClass.Однако это происходит перед каждым сценарием, поэтому переопределение TestExecutionListener.afterTestClass должно сработать.

0 голосов
/ 24 июня 2019

Вы можете сделать это через https://github.com/nosan/embedded-cassandra project

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import com.github.nosan.embedded.cassandra.test.spring.EmbeddedCassandra;

@SpringBootTest
@ActiveProfiles("INTEGRATION_TEST")
@EmbeddedCassandra(configurationFile = "cassandra.yaml", scripts = "cql/dataset1.cql")
public class TestStepDef {


}

@EmbeddedCassandra обрабатывается org.springframework.test.context.ContextCustomizer, поэтому у вас не будет проблем с запуском.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...