我有一个Spring Boot项目,该项目使用ElasticSearch来存储和索引产品。产品型号为:
@Document(indexName = "products", type = "product")
public class Product {
@Id
public String id;
private String[] barcode;
private String name;
private String description;
private String image;
private String detail;
private double price;
private double gain;
private List<Category> categories;
private Currency currency;
private boolean eliminated;
private String taxDescription;
private double taxRate;
private int taxId;
}
我正在对产品上的操作(例如搜索,更新等)进行集成测试,并且我需要使用相同的弹性服务器。我正在考虑仅出于测试目的创建索引,将其填充一些产品,然后在测试后删除它。可能吗?我该怎么办?
答案 0 :(得分:1)
我假设您在生产代码中使用了知名的Spring Data Repositories。像这样的东西可能会驻留在您的项目中:
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
Product findByName(String name);
}
因此您可以设置一个小的集成测试案例,如下所示:
@SpringBootTest
@RunWith(SpringRunner.class)
public class QueryIndexIT {
@Autowired
private ProductRepository repo;
@Autowired
private ElasticsearchTemplate template;
@Test
public void queryRepo() {
assertThat(template.indexExists(Product.class)).isTrue();
Product savedProduct = repo.save(new Product(null, "the name", "n/a"));
Product foundProduct = repo.findByName("the name");
assertThat(foundProduct).isEqualTo(savedProduct);
}
}
}
因此,基本上,您是在熟悉的Spring上下文中运行此集成测试,也许可以通过application-test.properties
进行一些改动。
要与网络中任何实际的ElasticSearch服务器实现独立性,您还可以使用Maven Docker Plugin来使自己脱钩。请特别注意我的executions
代码段中下面列出的pom.xml
部分。它会在运行任何集成测试之前启动一个新的ElasticSearch容器,并在测试终止后立即将其删除。因此,您可以使用干净且稳定的测试设置开始每个测试周期:
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.28.0</version>
<configuration>
<showLogs>true</showLogs>
<verbose>true</verbose>
<removeVolumes>true</removeVolumes>
<allContainers>true</allContainers>
<images>
<image>
<name>elasticsearch:6.6.2</name>
<alias>elasticsearch</alias>
<run>
<ports>
<port>9200:9200</port>
<port>9300:9300</port>
</ports>
<env>
<ES_JAVA_OPTS>-Xms512m -Xmx512m</ES_JAVA_OPTS>
<cluster.name>docker-cluster</cluster.name>
<discovery.type>single-node</discovery.type>
</env>
</run>
</image>
</images>
</configuration>
<executions>
<execution>
<id>prepare-containers</id>
<phase>pre-integration-test</phase>
<goals>
<goal>stop</goal>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>remove-containers</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
您可以找到有关所引用的ElasticSearch Docker映像in its description on the Docker Hub的更多信息。
因此您注意到,不必仅出于测试目的而创建单独的索引。将测试代码和生产代码(以及可能的配置)紧密结合在一起,以避免在生产运行时出现意外情况。
如果您想解决设置中可能出现的问题,还可以将您的方法与我在Github repository中为您准备的运行示例进行比较。
只需尝试使用
mvn clean verify -Dit.test=QueryIndexIT
。 玩得开心,并返回您的进度或评论!