简体   繁体   中英

Simulate / Mock a MySql Database for Unit Testing

For our applications we have created a series of healthchecks. One of these health checks checks whether or not a MySql database is up and running. In order to unit test this functionality I need to mock or simulate a database and run the health check against it.

To establish a connection to the MySql database being checked, we are using DriverManager.getConnection() . So we first tried to mock the return value of getConnection() . However, that is a static method and Mockito is unable to mock it. Then we turned to Powermock because it is able to mock static methods. Unfortunately, we found it to be poorly supported with JUnit5 and we had to clutter up our pom with a lot of dependencies. Not to mention the code was becoming overly complicated. In the end, we decide to look for other options besides mocking.

Basically, our health check just needs to make sure that the MySQL url, username, and password are correct and the database will accept a connection. Ideally, our unit tests would reflect these requirements.

So, our next idea is to use an In-Memory database, like this one from Baeldung. This seems like a great option but I'm worried it won't behave in the same way a real MySQL database will. Is there a way to create an In-memory MySQl database and establish a connection with DriverManager.getConnection() ? This would effectively simulate our real life health check

One option is to use the mysql jcabi maven plugin: mysql.jcabi.com

Please note version > 0.7 doesn't work on Windows.

This will actually setup an instance of MySQL, so it allows for one to test very mysql specific stuff, though the first run is slow.

So, a couple of questions will help drive your answer: are you doing anything highly MySQL specific? Do you want your app to be portable to other DBs?

If the answer is yes to the first one and no to the second one, probably use the jcabi plugin.

If the answer is no to the first, and yes to the second, you're probably pretty safe using H2.

If the answer is yes to both, you've got bigger problems :).

I generally try to keep my code away from DB vendor specificity and use libraries like JPA to abstract this. I can then assume that JPA (and impl) has tested across the supported DBs, and I'm good enough to run unit and integration tests with an in-memory DB like H2.

I generally also have some end-to-end testing in a prod-like env with the same DB setup as prod, in order to cover any vendor-specific quirks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM