嵌入式Cassandra运行多个测试用例时出现异常:Keyspace **不存在

时间:2014-02-19 23:38:02

标签: exception junit cassandra

模式创建在目标类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不存在”。

@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()中创建的键空间会消失?如何解决这个问题?感谢您提供任何指导。

1 个答案:

答案 0 :(得分:3)

每次测试后,

CassandraUnitTestExecutionListener 调用 cleanServer()。这会调用 EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(),它会丢弃所有非系统密钥空间。

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

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

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