【问题标题】:Exception when embedded Cassandra running multiple test cases: Keyspace ** does not exist嵌入式 Cassandra 运行多个测试用例时出现异常:Keyspace ** 不存在
【发布时间】:2014-02-20 12:44:42
【问题描述】:

架构创建在目标类 SimpleRepo.java 中完成。

public class SimpleRepo {

    private Cluster cluster;

    private Session session;

    private String keyspace = "app";

    private String table = "myTable";

    @Autowired
    public SimpleRepo(Cluster cluster) {
        this.cluster = cluster;
    }

    @PostConstruct
    private void init() {
        session = cluster.connect();
        createSchema();
    }

    public void createSchema() {
        .....
    }
}

当运行带有一个测试用例的 SimpleTest.java 时,它将通过。里面有两种情况运行时,只有第一种通过,第二种抛出异常:“com.datastax.driver.core.exceptions.InvalidQueryException: Keyspace app does not exist”。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class, SimpleRepo.class})
@TestExecutionListeners({CassandraUnitTestExecutionListener.class, DependencyInjectionTestExecutionListener.class})
@EmbeddedCassandra
public class SimpleTest {

    @Autowired
    private SimpleRepo simpleRepo;

    @Test
    public void testSave() throws Exception {
        ......
    }

    @Test
    public void testDel() throws IOException { 
        ......
    }
}

@Configuration
public class TestConfig {

    @Bean(destroyMethod = "shutdown")
    public Cluster cluster() throws ConfigurationException, TTransportException, IOException, InterruptedException{
        EmbeddedCassandraServerHelper.startEmbeddedCassandra();

        Cluster cluster = Cluster.builder()
                .addContactPoints("127.0.0.1")
                .withPort(9142)
                .build();

        return cluster;
    }
}

为什么在运行第二个测试用例时 createSchema() 中创建的键空间会消失?如何解决这个问题?感谢您的指导。

【问题讨论】:

  • 如果您显示测试用例代码会有所帮助。

标签: exception junit cassandra


【解决方案1】:

CassandraUnitTestExecutionListener 在每次测试后调用 cleanServer()。调用 EmbeddedCassandraServerHelper.cleanEmbeddedCassandra() 会删除所有非系统键空间。

您的代码只在 @PostConstruct 中创建您的键空间一次,因此只有第一个测试用例可以使用它。

看来您应该使用 @CassandraDataSet 为每个新测试初始化​​一个键空间

https://github.com/jsevellec/cassandra-unit/wiki/Spring-for-Cassandra-unit

【讨论】:

  • 非常感谢您的详细解释。如果键空间不存在,我尝试使用@CassandraDataSet 来初始化键空间。现在两种情况都可以通过了。
猜你喜欢
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 2020-04-12
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多