1

I am trying to find a way to unit test my MySQL dependant code. I know how I would like it to work but cannot find the solution that would work for me. I have looked into DBUnit, but it would seem (if I am not mistaken) that this would require a running database and just aids with the unit testing side of things. I would like some way to avoid running a mysql database when testing. What would work great would be some sort of MySQL spoof driver that actually stored data in memory, rather than needing to access a real persistent database.

In my code it is hard coded to access a MySQL database so I can't just inject some mock object. The way I would like it to work is that when my code calls:

DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);

It actually gets some other local database that can either be configured via maven or in the setUp of the maven test. I have looked into memory based databases such as HSQLDB but can't find a way for it to spoof the MySQL driver.

Are there any tools that provide what I am looking for? Do you have any good methods for testing MySQL dependant code?

flungo
  • 1,050
  • 1
  • 7
  • 21
  • http://stackoverflow.com/questions/10692398/how-do-i-make-a-mysql-database-run-completely-in-memory When unit testing remember to populate the database first before initiating the main program. – Tschallacka Feb 19 '14 at 12:05
  • I am not sure how I would use this without having an actual mysql server running. However that thought did make me think about an embedded mysql server to run during my unit tests. – flungo Feb 19 '14 at 12:25

1 Answers1

1

I have had several projects in which I had to do integrations test against a running MySql server. Instead of spending time setting it up every time, I developed a library that sets up a local running instance of MySQL every time you run your tests.

With that you get a test database that acts like the real thing (because it is) without having to set it up.

DBUnit is also a good alternative if you want to mock the database integration (as far as I know, there is no need for a real MySql server when using DBUnit).

StumpDK
  • 441
  • 5
  • 6
  • I think I ended up going with a similar approach using the MySQL embedded version as part of the test dependencies. I made a project called MyUnit which when extended would instantiate and destroy a MySQL database before and after tests. DBUnit looks of interest so will also take a look at that. The need for this has actually come up again on a project I am working on so I will take a look at the options again. – flungo Aug 01 '15 at 11:14
  • See http://stackoverflow.com/a/19279391/416300. This guy wrote a Maven plugin to start and stop a MySQL DB before and after his test. – summerbulb Jun 26 '16 at 12:33
  • That's right, and it can be used when developing Java applications. – StumpDK Jun 27 '16 at 04:13