EmbeddedMySql的使用
一. 简介
Embedded MySql库提供了一种在集成测试中运行真实MySql的方法。我们可以通过集成该jar包,实现内嵌式MySQL,不需要安装Mysql,即可进行数据库增删改查等相关操作。
二. 使用
1. 引入依赖
<!--embedded依赖-->
<dependency>
<groupId>com.wix</groupId>
<artifactId>wix-embedded-mysql</artifactId>
<version>4.6.1</version>
<scope>compile</scope>
</dependency>
2. 编写sql脚本
编写init.sql脚本,将脚本放在Resourse目录下
create table user (age INTEGER, name VARCHAR(10));
INSERT INTO user values(1, '你好!');
create table car (total INTEGER NOT NULL,carName VARCHAR(10),color VARCHAR(10));
INSERT INTO car values(10, '宝马7系','白色');
INSERT INTO car values(20, '奔驰C级','红色');
INSERT INTO car values(50, '大众速腾','黑色');
3. 编写配置类
import com.wix.mysql.EmbeddedMysql;
import com.wix.mysql.ScriptResolver;
import com.wix.mysql.config.Charset;
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.distribution.Version;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
@Configuration
public class EmbeddedConfig {
EmbeddedMysql mysqld;
@PostConstruct
public void startMysql() {
System.out.println(" 测试数据库执行了");
// MySql版本
MysqldConfig config = MysqldConfig.aMysqldConfig(Version.v5_7_10)
// 基础设置
.withCharset(Charset.UTF8)
.withPort(3306)
.withUser("agf", "123")
.withTimeZone("Asia/Shanghai")
.withTimeout(2, TimeUnit.MINUTES)
.withServerVariable("max_connect_errors", 666)
.build();
mysqld = EmbeddedMysql.anEmbeddedMysql(config)
//初始化数据表架构
.addSchema("tomato-center",
//sql脚本
ScriptResolver.classPathScript("init.sql"))
.start();
}
@PreDestroy
public void stopDb(){
System.out.println("stop");
mysqld.stop();
}
}
4. 编写单元测试
可以直接使用Springboo中Test下的测试类
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
System.out.println("测试embeddedMysql");
}
}
5. 执行单元测试
可以看到执行成功了,但好像我们一点感知都没有,我们的sql脚本执行结果呢?
其实这个过程帮我们创建了数据库,并且执行完了我们的sql脚本,只是执行完后关闭了数据库,这个过程我们是无感知的,如果我们的sql有问题就会直接报错,如果不报错,就说明我的脚本执行成功了。
2022-08-10 15:30:17.555 INFO 15908 --- [ main] c.n.n.NacosProviderApplicationTests : Starting NacosProviderApplicationTests using Java 1.8.0_181 on ISS490002001977 with PID 15908 (started by issuser in D:\springcloud_nacos\nacos_provider)
2022-08-10 15:30:17.555 INFO 15908 --- [ main] c.n.n.NacosProviderApplicationTests : No active profile set, falling back to default profiles: default
2022-08-10 15:30:18.441 INFO 15908 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=f4c71473-a16a-398e-82db-2f0db57e0c80
测试机数据库执行了
2022-08-10 15:30:18.577 INFO 15908 --- [ main] com.wix.mysql.EmbeddedMysql : Preparing EmbeddedMysql version 'Version 5.7.10'...
2022-08-10 15:30:18.958 INFO 15908 --- [ main] com.wix.mysql.MysqldExecutable : Preparing mysqld for startup
2022-08-10 15:30:27.846 INFO 15908 --- [ main] com.wix.mysql.MysqldExecutable : Starting MysqldProcess
2022-08-10 15:30:29.948 INFO 15908 --- [ main] d.f.embed.process.runtime.Executable : start com.wix.mysql.config.MysqldConfig@5533dc72[charset=Charset{charset='utf8', collate='utf8_general_ci'},port=3306,serverVariables={com.wix.mysql.config.MysqldConfig$ServerVariable@164a62bf[name=max_connect_errors,value=666]},tempDir=target/,timeZone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],timeout=com.wix.mysql.config.MysqldConfig$Timeout@7bc6d27a[length=2,unit=MINUTES],user=com.wix.mysql.config.MysqldConfig$User@6ab4ba9f[name=agf],_supportConfig=com.wix.mysql.config.MysqldConfig$1@4c59e45e,version=Version 5.7.10]
------com.wix.mysql.EmbeddedMysql@713064e8
2022-08-10 15:30:33.883 INFO 15908 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2022-08-10 15:30:34.524 INFO 15908 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'Nacos-Watch-Task-Scheduler'
2022-08-10 15:30:35.531 INFO 15908 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 17 endpoint(s) beneath base path '/actuator'
2022-08-10 15:30:36.050 INFO 15908 --- [ main] c.n.n.NacosProviderApplicationTests : Started NacosProviderApplicationTests in 19.037 seconds (JVM running for 20.124)
测试embeddedMysql
2022-08-10 15:30:36.517 WARN 15908 --- [ Thread-9] c.a.n.common.http.HttpClientBeanHolder : [HttpClientBeanHolder] Start destroying common HttpClient
2022-08-10 15:30:36.517 INFO 15908 --- [ Thread-3] com.wix.mysql.MysqldProcess : try to stop mysqld
2022-08-10 15:30:36.517 WARN 15908 --- [ Thread-9] c.a.n.common.http.HttpClientBeanHolder : [HttpClientBeanHolder] Destruction of the end
2022-08-10 15:30:36.517 WARN 15908 --- [ Thread-15] c.a.nacos.common.notify.NotifyCenter : [NotifyCenter] Start destroying Publisher
2022-08-10 15:30:36.517 WARN 15908 --- [ Thread-15] c.a.nacos.common.notify.NotifyCenter : [NotifyCenter] Destruction of the end
2022-08-10 15:30:36.525 INFO 15908 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'Nacos-Watch-Task-Scheduler'
2022-08-10 15:30:43.098 INFO 15908 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
6. 复现执行结果
我们如果想看我们sql脚本的执行结果,最直观的方式是看我们脚本中创建的表在数据库中是否存在。我们可以在程序关闭数据库前打个断点然后进行验证,但是这一步必须依赖本地mysql数据库(本地没有的话需要安装一个)
打完断电后执行测试方法,程序执行到断电后,我们用配置的信息去链接本地mysql数据库。
测试连接,连接成功。
这样在数据中就能看到我们sql脚本执行的结果了。
7. 总结
Embedded MySql就通过sql脚本的方式虚拟测试接口,我们可以通过sql脚本中去模拟我们需要的表结构,数据字段,以及复杂的sql语句,省缺我们对特定数据库表的的依赖以及数据源的配置。