Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing - database and fixtures

I am just starting to get into unit testing and cant see an easy way to do a lot of test cases due to the interaction with a database.

Is there a standard method/process for unit testing where database access (read and write) is required in order to assert tests?

The best I can come up with so far is to have a config file used to bootstrap my app using a different db connection and then use the startup method to copy over the live db to a db used in isolation for tests?

Am I close? Or is there a better approach to this?

like image 945
Marty Wallace Avatar asked May 26 '12 20:05

Marty Wallace


1 Answers

Your business logic shouldn't directly interact with the Database. Instead it should go through a data access layer that you can fake and mock in the context of unit testing. Look into mocking frameworks to do the mocking for you. Your tests should not depend on a database at all. Instead you should specify the data returned from your data access layer explicitly, and then ensure that your business logic behaves correctly with that information.

Testing that the program works with a DB attached is more of an integration test, and those have a lot of costs associated with them. They are slower (so it's harder to run them every time you compile), and more complicated (so they require more time and effort to maintain). If you can get simpler unit tests in place, I would recommend you do that first. Later you can add integration tests that might use the DB as well, but you'll get the most value from adding simpler unit tests first.

like image 161
Oleksi Avatar answered Oct 23 '22 20:10

Oleksi