views:

62

answers:

3

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?

A: 

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.

Fredrick
+3  A: 

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).

jgauffin
A: 

I presume you want to test that the interface between your code and the db (orm, stored procedures...) is correctly implemented and in this case you'll need to actually be plugged to a db. Otherwise you'll end up testing your stub and if it does not share an interface with your actual db connection code, it's useless.

vc 74