当前位置: 首页 > news >正文

Spring Boot集成testcontainers快速入门Demo

1.什么是testcontainers?

Testcontainers 是一个用于创建临时 Docker 容器进行单元测试的 Java 库。当我们想要避免使用实际服务器进行测试时,它非常有用。,官网介绍称支持50多种组件。​

 

应用场景

数据访问层集成测试:

使用MySQL,PostgreSQL或Oracle数据库的容器化实例测试您的数据访问层代码,但无需在开发人员的计算机上进行复杂的设置,并且测试将始终从已知的数据库状态开始,避免“垃圾”数据的干扰。也可以使用任何其他可以容器化的数据库类型。

应用程序集成测试:

用于在具有相关性(例如数据库,消息队列或Web服务器)的短期测试模式下运行应用程序。

UI /验收测试:

使用与Selenium兼容的容器化Web浏览器进行自动化UI测试。每个测试都可以获取浏览器的新实例,而无需担心浏览器状态,插件版本或浏览器自动升级。您将获得每个测试会话或测试失败的视频记录。

2.代码工程

实验目的:在 Spring Boot 中使用 Testcontainers 测试 Redis。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>testcontainers</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers</artifactId><version>1.17.2</version><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>
</project>

entity

package com.et.testcontainers.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.redis.core.RedisHash;import java.io.Serializable;@RedisHash("product")
@AllArgsConstructor
@Data
public class Product implements Serializable {private String id;private String name;private double price;}

service

package com.et.testcontainers.service;import com.et.testcontainers.Repository.ProductRepository;
import com.et.testcontainers.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class ProductService {@Autowiredprivate ProductRepository productRepository;public Product getProduct(String id) {return productRepository.findById(id).orElse(null);}public void createProduct(Product product) {productRepository.save(product);}
}

Repository

package com.et.testcontainers.Repository;import com.et.testcontainers.entity.Product;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;@Repository
public interface ProductRepository extends CrudRepository<Product, String> {
}

appliication.properties

spring.redis.host=127.0.0.1
spring.redis.port=6379

启动类

package com.et.testcontainers;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.

3.测试

编写测试类

package com.et.testcontainers;import com.et.testcontainers.entity.Product;
import com.et.testcontainers.service.ProductService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;import static org.junit.Assert.assertEquals;@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoTests {private static Logger log = LoggerFactory.getLogger(DemoTests.class);@AutowiredProductService productService;@Beforepublic void before()  {log.info("init some data");}@Afterpublic void after(){log.info("clean some data");}@Testpublic void execute()  {log.info("your method test Code");}static {GenericContainer<?> redis =new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine")).withExposedPorts(6379);redis.start();log.info(redis.getHost());log.info(redis.getMappedPort(6379).toString());System.setProperty("spring.redis.host", redis.getHost());System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString());}@Testpublic void givenProductCreated_whenGettingProductById_thenProductExistsAndHasSameProperties() {Product product = new Product("1", "Test Product", 10.0);productService.createProduct(product);Product productFromDb = productService.getProduct("1");assertEquals("1", productFromDb.getId());assertEquals("Test Product", productFromDb.getName());assertEquals(10.0, productFromDb.getPrice(),0.001);}
}

执行测试用例,全部通过,这样就可以脱离实际环境测试我们的代码,每次也不用因为环境不对而跳过单元测试

4.参考

  • 使用 Testcontainers 测试 Redis - spring 中文网
  • Testcontainers
  • Spring Boot集成testcontainers快速入门Demo | Harries Blog™

相关文章:

  • 基于地理坐标的高阶几何编辑工具算法(5)——合并相交面
  • Python操作MySQL实战
  • 椋鸟C++笔记#3:类的默认成员函数
  • 【html】网页布局模板01---简谱风
  • Java_IO流学习
  • GESP 四级冲刺训练营(1):字符串
  • linux内核符号表
  • 踩坑——纪实
  • VUE 页面生命周期基本知识点
  • 瑞芯微RV1126——ffmpeg环境搭建
  • 国产linux系统(银河麒麟,统信uos)使用 PageOffice 国产版在线编辑word文件,同时保存数据和文件
  • Springboot 自定义线程池 ThreadPoolTaskExecutor
  • 标准库算法
  • Android 观察者模式(OBSERVER)应用详解
  • Spring与Netty底层源码解析
  • canvas绘制圆角头像
  • DOM的那些事
  • Electron入门介绍
  • Hibernate最全面试题
  • Java 网络编程(2):UDP 的使用
  • JavaScript 是如何工作的:WebRTC 和对等网络的机制!
  • js写一个简单的选项卡
  • LeetCode541. Reverse String II -- 按步长反转字符串
  • miaov-React 最佳入门
  • nginx 配置多 域名 + 多 https
  • opencv python Meanshift 和 Camshift
  • PAT A1120
  • python 装饰器(一)
  • scrapy学习之路4(itemloder的使用)
  • Spark RDD学习: aggregate函数
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • 和 || 运算
  • 蓝海存储开关机注意事项总结
  • 类orAPI - 收藏集 - 掘金
  • 利用阿里云 OSS 搭建私有 Docker 仓库
  • 区块链技术特点之去中心化特性
  • 一道面试题引发的“血案”
  • 一天一个设计模式之JS实现——适配器模式
  • 优化 Vue 项目编译文件大小
  • 智能情侣枕Pillow Talk,倾听彼此的心跳
  • ​ 轻量应用服务器:亚马逊云科技打造全球领先的云计算解决方案
  • ​如何使用ArcGIS Pro制作渐变河流效果
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • #Z2294. 打印树的直径
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • (13)Latex:基于ΤΕΧ的自动排版系统——写论文必备
  • (8)STL算法之替换
  • (function(){})()的分步解析
  • (k8s)Kubernetes本地存储接入
  • (poj1.2.1)1970(筛选法模拟)
  • (ZT)北大教授朱青生给学生的一封信:大学,更是一个科学的保证
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (附源码)计算机毕业设计ssm基于Internet快递柜管理系统
  • (六)DockerCompose安装与配置