Is there a way to run MySQL in-memory for JUnit test cases?

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

Leave a Comment