有没有办法在JUnit测试用例中运行MySQL内存? [英] Is there a way to run MySQL in-memory for JUnit test cases?

查看:165
本文介绍了有没有办法在JUnit测试用例中运行MySQL内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想为访问MySQL数据库的服务添加测试用例,我想重新创建整个模式(对于某些场景,也只是使用带有每个测试用例所需数据的MySQL转储文件)。我环顾四周,发现有些人使用SQLite / H2和其他人来做这件事,但是如果有任何方法可以在内存中运行MySQL,我只是徘徊,所以我不需要担心MySQL的任何特定内容方言我可能正在使用我们的服务。

解决方案

使用与MySQL完全兼容的内存数据库的最简单方法可以在JUnit中使用测试用例是imho MariaDB4j。
你只需要一个Gradle(/ Maven)依赖项( http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mariaDB4j%22 )以及几行代码:

  DB database = DB.newEmbeddedDB(3306); 
database.start();
连接连接= DriverManager.getConnection(jdbc:mysql:// localhost / test,root,);

可以通过



$ b <$包含启动脚本p $ p> database.source( 路径/到/ resource.sql);

有关GitHub自述文件的更多信息:
https://github.com/vorburger/MariaDB4j



编辑:
我添加一些提示:MariaDB4j似乎在系统临时文件夹中添加文件。所以它将以嵌入的方式工作,这意味着不需要安装任何东西,你可以通过你想要的构建工具使用依赖。但它不是真正的仅内存解决方案,因此我们不能再谈论单元测试,因为单元测试不能依赖于文件或数据库


I'm just trying to add test cases for services accessing a MySQL DB, and I would like to recreate the whole schema (and for some scenarios also just use a MySQL dump file with the data needed for each test case). I was looking around and found some guys using SQLite / H2 and others to do this, but I'm just wandering if there is any way to run MySQL in-memory so I don't need to worry about anything specific to the the MySQL dialect I might be using on our services.

解决方案

The easiest way for using an in memory database that is fully compatible to MySQL and can be used within JUnit test cases is imho MariaDB4j. you just need a Gradle (/Maven) dependency (http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mariaDB4j%22) and a few lines of code to start:

DB database = DB.newEmbeddedDB(3306);
database.start();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");

a startup script can be included via

database.source("path/to/resource.sql");

More information on GitHub readme: https://github.com/vorburger/MariaDB4j

EDIT: I have a add some hints to this answer: The MariaDB4j seems to add files in the systems temporary folder. So it will work in an embedded way which means there is no need to install anything and you can just use the dependency via your desired build tool. But it's not a true in-memory-only solution and therefore we cannot speak of unit tests anymore because unit tests mustn't rely on files or databases

这篇关于有没有办法在JUnit测试用例中运行MySQL内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆