1. Overview
1.概述
Generally, we use Spring’s auto-configuration system such as @SpringBootTest for testing Spring Boot applications. But this results in lots of imports of auto-configured components.
通常,我们使用Spring的自动配置系统,如@SpringBootTest来测试Spring Boot应用程序。但是这导致了大量自动配置组件的导入。
However, it always helps to load only the required parts to test a slice of the application. For this reason, Spring Boot provides many annotations for slice testing. Above all, each of these Spring annotations loads a very limited set of auto-configured components that are required for a particular layer.
然而,只加载所需的部分来测试应用程序的一个片断总是有帮助的。为此,Spring Boot为切片测试提供了许多注释。最重要的是,这些Spring注释中的每一个都会加载一个非常有限的自动配置的组件集,这些组件是特定层所需的。
In this tutorial, we’ll focus on testing a Cassandra database slice of a Spring Boot application in order to learn about @DataCassandraTest annotation provided by Spring.
在本教程中,我们将重点测试Spring Boot应用程序的Cassandra数据库片,以便了解@DataCassandraTest由Spring提供的注解。
Additionally, we’ll look at a small Cassandra-based Spring Boot application in action.
另外,我们将看看一个基于Cassandra的小型Spring Boot应用的运行情况。
And, if you’re running Cassandra in production, you can definitely cut out the complexity of running and maintaining your own server and use the Astra database instead, which is a cloud-based database built on Apache Cassandra.
而且,如果您在生产中运行 Cassandra,您绝对可以省去运行和维护自己的服务器的复杂性,而使用Astra 数据库,而这是基于 Apache Cassandra 的云数据库。
2. Maven Dependencies
2.Maven的依赖性
To use the @DataCassandraTest annotation in our Cassandra Spring Boot application, we have to add the spring-boot-starter-test dependency:
为了在我们的Cassandra Spring Boot应用程序中使用@DataCassandraTest注解,我们必须添加spring-boot-starter-test依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.3</version>
<scope>test</scope>
</dependency>
Spring’s spring-boot-test-autoconfigure is part of the spring-boot-starter-test library, and it contains lots of auto-configuration components for testing different slices of an application.
Spring的 spring-boot-test-autoconfigure是 spring-boot-starter-test库,它包含很多自动配置组件,用于测试应用程序的不同片区。
Generally, this test annotation has a pattern of @XXXTest.
一般来说,这个测试注解的模式为@XXXTest.。
@DataCassandraTest annotation imports the following Spring data auto-configuration components:
@DataCassandraTest注解导入了以下Spring数据自动配置组件:。
- CacheAutoConfiguration
- CassandraAutoConfiguration
- CassandraDataAutoConfiguration
- CassandraReactiveDataAutoConfiguration
- CassandraReactiveRepositoriesAutoConfiguration
- CassandraRepositoriesAutoConfiguration
3. Example Cassandra Spring Boot Application
3.Cassandra Spring Boot应用实例</b
To illustrate these concepts, we have a simple Spring Boot web application whose main domain is vehicle inventory.
为了说明这些概念,我们有一个简单的Spring Boot网络应用,其主要领域是车辆库存。
To keep it simple, this application provides basic CRUD operations of the inventory data.
为了保持简单,这个应用程序提供了基本的CRUD库存数据的操作。
3.1. Cassandra Maven Dependency
3.1.Cassandra的Maven依赖
Spring provides the spring-boot-starter-data-cassandra module for Cassandra data:
Spring提供 spring-boot-starter-data-cassandra Cassandra数据的模块:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
<version>2.5.3</version>
</dependency>
We also need the dependency on the Datastax Cassandra’s java-driver-core to enable cluster connectivity and request execution:
我们还需要依赖Datastax Cassandra的 java-driver-core 以启用集群连接和请求执行:
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-core</artifactId>
<version>4.13.0</version>
</dependency>
3.2. Cassandra Configuration
3.2.Cassandra配置
Here our CassandraConfig class extends Spring’s AbstractCassandraConfiguration, which is the base class for Spring Data Cassandra configuration.
这里我们的CassandraConfig类扩展了Spring的AbstractCassandraConfiguration,它是Spring Data Cassandra配置的基础类。
This spring class is used to configure the Cassandra client application with CqlSession to connect to the Cassandra cluster.
该Spring类用于用CqlSession配置 Cassandra 客户应用程序,以连接到 Cassandra 集群。
Additionally, we can configure the keyspace name and cluster host:
另外,我们可以配置钥匙空间名称和集群主机:。
@Configuration
public class CassandraConfig extends AbstractCassandraConfiguration {
@Override
protected String getKeyspaceName() {
return "inventory";
}
@Override
public String getContactPoints() {
return "localhost";
}
@Override
protected String getLocalDataCenter() {
return "datacenter1";
}
}
4. Data Model
4.数据模型
The following Cassandra Query Language (CQL) creates Cassandra keyspace by name inventory:
以下<a href=”https://docs.datastax.com/en/cql-oss/3.x/cql/cql_using/useCreateKeyspace.
CREATE KEYSPACE inventory
WITH replication = {
'class' : 'NetworkTopologyStrategy',
'datacenter1' : 3
};
And this CQL creates a Cassandra table by name vehicles in inventory keyspace:
而这 CQL 按名称创建一个Cassandra表车辆在库存关键空间中。
use inventory;
CREATE TABLE vehicles (
vin text PRIMARY KEY,
year int,
make varchar,
model varchar
);
5. @DataCassandraTest Usage
5.@DataCassandraTest用法
Let’s look at how we can use @DataCassandraTest in unit tests to test the data layer of the application.
让我们来看看我们如何在单元测试中使用@DataCassandraTest来测试应用程序的数据层。
The @DataCassandraTest annotation imports the required Cassandra auto-configuration modules, which includes scanning @Table and @Repository components. As a result, it makes it possible to @Autowire the Repository class.
@DataCassandraTest注解导入了所需的Cassandra自动配置模块,其中包括扫描@Table和@Repository组件。因此,它使得@Autowire的类成为可能。
However, it does not scan and import the regular @Component and @ConfigurationProperties beans.
然而,它没有扫描和导入常规的@Component和@ConfigurationPropertiesBean。
Additionally, with JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class).
另外,在JUnit 4中,该注解应与@RunWith(SpringRunner.class)结合使用。
5.1. Integration Test Class
5.1.集成测试类</b
Here is the InventoryServiceIntegrationTest class with the @DataCassandraTest annotation and the repository @Autowired:
这里是InventoryServiceIntegrationTest 类与@DataCassandraTest注解和资源库@Autowired:。
@RunWith(SpringRunner.class)
@DataCassandraTest
@Import(CassandraConfig.class)
public class InventoryServiceIntegrationTest {
@Autowired
private InventoryRepository repository;
@Test
public void givenVehiclesInDBInitially_whenRetrieved_thenReturnAllVehiclesFromDB() {
List<Vehicle> vehicles = repository.findAllVehicles();
assertThat(vehicles).isNotNull();
assertThat(vehicles).isNotEmpty();
}
}
We’ve also added a simple test method above.
我们也在上面添加了一个简单的测试方法。
To make it easier to run this test, we’ll use a DockerCompose Test Container, which sets up a three-node Cassandra cluster:
为了更容易地运行这个测试,我们将使用DockerCompose测试容器,它设置了一个三节点的Cassandra集群。
public class InventoryServiceLiveTest {
// ...
public static DockerComposeContainer container =
new DockerComposeContainer(new File("src/test/resources/compose-test.yml"));
@BeforeAll
static void beforeAll() {
container.start();
}
@AfterAll
static void afterAll() {
container.stop();
}
}
You can find the compose-test.yml file in the GitHub project here.
你可以在GitHub项目中找到 compos-test.yml 文件这里.
5.2. Repository Class
5.2.存储库类</b
The example repository class InventoryRepository defines a few custom JPA methods:
示例仓库类InventoryRepository定义了几个自定义的JPA方法:
@Repository
public interface InventoryRepository extends CrudRepository<Vehicle, String> {
@Query("select * from vehicles")
List<Vehicle> findAllVehicles();
Optional<Vehicle> findByVin(@Param("vin") String vin);
void deleteByVin(String vin);
}
We’ll also define a Consistency level of “local-quorum”, which implies a strong consistency, by adding this property to the application.yml file:
我们还将定义一个 “本地-法定人数 “的一致性级别,这意味着强一致性,方法是将这个属性添加到application.yml文件:
spring:
data:
cassandra:
request:
consistency: local-quorum
6. Other @DataXXXTest Annotations
6.其他@DataXXXTest 注释
Following are some of the other similar annotations to test the database layer of any application:
以下是一些其他类似的注释,用于测试任何应用程序的数据库层:。
- @DataJpaTest imports JPA repositories, @Entity classes, etc.
- @DataJdbcTest imports Spring Data repositories, JdbcTemplate, etc.
- @DataMongoTest imports Spring Data MongoDB repositories, Mongo templates and @Document classes
- @DataNeo4jTest imports Spring Data Neo4j repositories, @Node classes
- @DataRedisTest imports Spring Data Redis repositories, @RedisHash
Please visit the Spring documentation for more test annotations and detailed information.
请访问 Spring文档以获得更多的测试注释和详细信息。
7. Conclusion
7.结论
In this article, we learned how @DataCassandraTest annotation loads a few Spring Data Cassandra auto-configuration components. As a result, it avoids loading many unwanted Spring context modules.
在这篇文章中,我们了解了@DataCassandraTest注解如何加载少数Spring Data Cassandra自动配置组件。因此,它避免了加载许多不需要的Spring上下文模块。。
As always, the full source code is available over on GitHub.
一如既往,完整的源代码可在GitHub上获得。。