Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Database Class

This has probably been asked many times but here it goes :

I have a class full of db connections

open connection
query db
read values
close connection

How should I unit test this stuff?

Do I need to create a fake database? I guess I could mock the MySql classes (for c#), but that's also a lot of work.

Some of the statements are "INSERT INTO", what should I do about this?

like image 235
Eric Avatar asked Oct 26 '10 18:10

Eric


2 Answers

Stuff that are hard to test is often tightly coupled or not following the Single Responsibility principle.

First of all. Split your datalayer. Look at the repository pattern. Each entity (table or view) should have it's own class fetching data.

Use data interfaces instead of specific driver implementation: IDbConnection instead of SqlConnection. Use DbProviderFactory to get the proper connection implementation. Then use connection.CreateCommand() to get a command etc.

Doing all that would make it a whole lot easier to test your data layer. And remember, the datalyer should not have any logic. It's only purpose is to load data from a data source.

But if you don't want to change stuff: Working against a database is the easiest way. Remove all data and insert new test data before each test (to remove any changes during a previous test).

like image 107
jgauffin Avatar answered Oct 20 '22 08:10

jgauffin


Easiest would be to create a new test db and make some insert querys and then store the result sets in a list or something and then just run it with the debugger to see if it's stores the resultset in the list you've created.

Don t have any intsert into in the source code, use sql management studios and make the inserts there instead until you know that the connections and everything works. Just tab out all those values for now.

like image 43
Fredrick Avatar answered Oct 20 '22 08:10

Fredrick