EmbeddedCassandra: не удается выполнить модульные тесты

Я использую EmbeddedCassandraServerHelper для выполнения модульных тестов. Вот мой pom

<dependencies>
   <dependency>
      <groupId>org.apache.nifi</groupId>
      <artifactId>nifi-api</artifactId>
      <version>1.4.0</version>
   </dependency>
   <dependency>
      <groupId>org.apache.nifi</groupId>
      <artifactId>nifi-utils</artifactId>
      <version>1.4.0</version>
   </dependency>
   <dependency>
      <groupId>org.apache.nifi</groupId>
      <artifactId>nifi-mock</artifactId>
      <version>1.4.0</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.7.25</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.54</version>
   </dependency>
   <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.2</version>
   </dependency>
   <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.10.8</version>
   </dependency>
   <dependency>
      <groupId>com.datastax.cassandra</groupId>
      <artifactId>cassandra-driver-core</artifactId>
      <version>3.4.0</version>
   </dependency>
   <dependency>
      <groupId>com.datastax.cassandra</groupId>
      <artifactId>cassandra-driver-mapping</artifactId>
      <version>3.4.0</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/com.datastax.cassandra/cassandra-driver-extras -->
   <dependency>
      <groupId>com.datastax.cassandra</groupId>
      <artifactId>cassandra-driver-extras</artifactId>
      <version>3.4.0</version>
   </dependency>
   <dependency>
      <groupId>org.cassandraunit</groupId>
      <artifactId>cassandra-unit</artifactId>
      <version>3.3.0.2</version>
      <scope>test</scope>
   </dependency>
</dependencies>

Я ссылаюсь на документацию на

https://github.com/jsevellec/cassandra-unit/wiki/How-to-use-it-in-your-code

Сначала я попробовал

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private final static Logger logger = LoggerFactory.getLogger(MyTestClass.class);
logger.info("Starting EmbeddedCassandra");


EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.CASSANDRA_RNDPORT_YML_FILE);

и я получил

org.apache.cassandra.exceptions.ConfigurationException: Invalid yaml: file:/path/to/project/target/embeddedCassandra/cu-cassandra-rndport.yaml
 Error: null; Can't construct a java object for tag:yaml.org,2002:org.apache.cassandra.config.Config; exception=java.lang.reflect.InvocationTargetException;  in 'reader', line 10, column 1:
    cluster_name: 'Test Cluster'
    ^
    at org.apache.cassandra.config.YamlConfigurationLoader.loadConfig(YamlConfigurationLoader.java:131)
    at org.apache.cassandra.config.YamlConfigurationLoader.loadConfig(YamlConfigurationLoader.java:101)
    at org.apache.cassandra.config.DatabaseDescriptor.loadConfig(DatabaseDescriptor.java:261)
    at org.apache.cassandra.config.DatabaseDescriptor.daemonInitialization(DatabaseDescriptor.java:140)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:137)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:102)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:81)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:77)
    at com.ibm.whi.breastadvisor.controller.processors.test.StagerBAControllerProcessorUnitTest.setUp(StagerBAControllerProcessorUnitTest.java:98)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

java.lang.NullPointerException
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.dropKeyspacesWithNativeDriver(EmbeddedCassandraServerHelper.java:268)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.dropKeyspaces(EmbeddedCassandraServerHelper.java:264)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(EmbeddedCassandraServerHelper.java:200)
    at com.ibm.whi.breastadvisor.controller.processors.test.StagerBAControllerProcessorUnitTest.cassandraCleanup(StagerBAControllerProcessorUnitTest.java:145)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Файл был очень сильным и синтаксически правильным. Я получил содержимое файла yml из

https://github.com/jsevellec/cassandra-unit/blob/master/cassandra-unit/src/main/resources/cu-cassandra-rndport.yaml

Тогда я нашел решение здесь

https://github.com/jsevellec/cassandra-unit-examples/issues/8

i обновил мой pom как

        <dependency>
            <groupId>org.cassandraunit</groupId>
            <artifactId>cassandra-unit</artifactId>
            <version>3.3.0.2</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.httpcomponents</groupId>
                    <artifactId>httpclient</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>commons-codec</groupId>
                    <artifactId>commons-codec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

но теперь я получаю

Exception (java.lang.ClassCastException) encountered during startup: org.slf4j.impl.SimpleLogger cannot be cast to ch.qos.logback.classic.Logger
java.lang.ClassCastException: org.slf4j.impl.SimpleLogger cannot be cast to ch.qos.logback.classic.Logger
    at org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager.install(ThreadAwareSecurityManager.java:92)
    at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:192)
    at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:600)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.lambda$startEmbeddedCassandra$1(EmbeddedCassandraServerHelper.java:144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[pool-2-thread-1] ERROR org.apache.cassandra.service.CassandraDaemon - Exception encountered during startup
java.lang.ClassCastException: org.slf4j.impl.SimpleLogger cannot be cast to ch.qos.logback.classic.Logger
    at org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager.install(ThreadAwareSecurityManager.java:92)
    at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:192)
    at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:600)
    at org.cassandraunit.utils.EmbeddedCassandraServerHelper.lambda$startEmbeddedCassandra$1(EmbeddedCassandraServerHelper.java:144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

как я могу исправить эти ошибки? Я просто хочу запустить простой встроенный сервер cassandra для тестирования.

Ответ 1

Из последней трассировки стека, которую вы отправили, я предполагаю, что вам нужно удалить зависимости logback-core и logback-classic от cassandra-unit в pom.xml.

Ваши зависимости будут выглядеть следующим образом:

<dependency>
    <groupId>org.cassandraunit</groupId>
    <artifactId>cassandra-unit</artifactId>
    <version>3.3.0.2</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </exclusion>
        <exclusion>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Сообщите мне, если у вас все еще есть проблема

Ответ 2

Я использую встроенную кассандру таким образом (с groovy, но вы можете ее портировать):

Соответствующие части pom:

       <dependency>
        <groupId>org.cassandraunit</groupId>
        <artifactId>cassandra-unit-spring</artifactId>
        <version>3.1.1.0</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.cassandraunit</groupId>
                <artifactId>cassandra-unit</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>netty-handler</artifactId>
                <groupId>io.netty</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.cassandraunit</groupId>
        <artifactId>cassandra-unit</artifactId>
        <classifier>shaded</classifier>
        <exclusions>
            <exclusion>
                <artifactId>netty-handler</artifactId>
                <groupId>io.netty</groupId>
            </exclusion>
        </exclusions>
        <version>3.1.1.0</version>
        <scope>test</scope>
    </dependency>

Startup:

    @Bean
private Session startup() {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra(10000)
    if(EmbeddedCassandraServerHelper.getSession() != null && EmbeddedCassandraServerHelper.getSession().getCluster().getMetadata().getKeyspace("testkeyspace") != null) {
        return EmbeddedCassandraServerHelper.getSession()
    }
    ConstantReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(1)
    FallthroughRetryPolicy retryPolicy = FallthroughRetryPolicy.INSTANCE
    Cluster cluster = new Cluster.Builder().addContactPoints("127.0.0.1").withPort(9142).withReconnectionPolicy(reconnectionPolicy).withRetryPolicy(retryPolicy).build()

    if( environment.getProperty("cassandra-debug").equalsIgnoreCase("true")) {
        cluster.register(getLatencyTracker())
    }

    Session session = cluster.connect()
    CQLDataLoader dataLoader = new CQLDataLoader(session)
    dataLoader.load(new ClassPathCQLDataSet("db/tables.cql", true, "testkeyspace"))

    CacheManager.getInstance().shutdown()

    return session
}

Хитрость заключается в том, чтобы встроенная кассандра работала до запуска вашего приложения. Я архивирую это, но используя аннотацию Import в своем абстрактном тестовом классе:

@Import(IntegrationConfiguration.class)
abstract class ComponentTestSpecification extends Specification {
}

В IntegrationConfiguration.class содержится запуск cassandra bean