mysql embedded是什么

文 / @UTHEME

Embedded MySQL是一种在集成测试中运行真实MySQL的方法,它提供了内嵌式MySQL的方式,不需要安装MySQL就可以进行数据库增删改查等相关操作。本教程的操作环境是Windows10系统,MySQL8版本,Dell G3电脑。

首先要引入maven依赖,即在pom.xml文件中添加以下代码:

```

com.wix
wix-embedded-mysql
4.6.1
test

```

然后,我们需要配置内嵌数据库启动的相关参数,即创建一个EmbeddedMysqlConfig类来加载MySQL,并将其作为单元测试的依赖项。以下是Java代码的使用示例:

```
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.EmbeddedMysql;
import static com.wix.mysql.ScriptResolver;
import java.util.concurrent.TimeUnit;
import static com.wix.mysql.config.MysqldConfig.aMysqldConfig;
import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql;
import static com.wix.mysql.distribution.Version.v5_6_23;
import static com.wix.mysql.config.Charset.UTF8;

public class EmbeddedMysqlConfig {

private EmbeddedMysql mysqld;

public void launchDb() {
MysqldConfig config = aMysqldConfig(v5_6_23)
.withCharset(UTF8)
.withPort(13306)
.withUser("root", "123456")
.withTimeZone("Asia/Shanghai")
.withTimeout(2, TimeUnit.MINUTES)
.withServerVariable("max_connect_errors", 666)
.build();

mysqld = anEmbeddedMysql(config)
.addSchema("aschema", ScriptResolver.classPathScript("db/001_init.sql"))
.addSchema("aschema2", ScriptResolver.classPathScripts("db/*.sql"))
.start();
}

public void stopDb() {
mysqld.stop();
}
}
```

最后,我们需要将启动配置到单元测试中。我们可以重写SpringJUnit4ClassRunner类,用于在测试之前自动启动内嵌MySQL。以下是一个JUnit测试示例:

```
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EmbeddedMysqlTests {

@Autowired
private ApplicationContext context;

@ClassRule
public static EmbeddedMysqlConfig mysqld = new EmbeddedMysqlConfig();

@BeforeClass
public static void before() {
mysqld.launchDb();
}

@AfterClass
public static void after() {
mysqld.stopDb();
}

@Test
public void test() throws Exception {
// perform tests here
}

}
```

以上就是Embedded MySQL的使用方法。更多信息可以参考GitHub源码。

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。