views:

90

answers:

1

I need to test a class who's return value depends on values from a database. I could just hit the database in the unit test but those values could change. Is there a standard solution to this?

+4  A: 

The standard answer is to redesign you class so you can mock out the dependency. This is typically done by injecting your datasource as an interface into you class.

e.g. You may have a class that acts like below

class John 
{
     public John() { }
     public void Load()
     {
          // call to db in here e.g SQLCommand
     }                  
}

Load is dependent on the SQLCommand so you will always need to call a db for this

If you inject a datasource interface you have more flexibility

e.g.

class John 
{    IDataSource _db;
     public John(IDataSource db) 
     {
        _db = db;
     }
     public void Load()
     {
        _db.Load("John"); // IDataSource can now be either SQL 
        //or hardcoded or what ever much easier to test
     }                  
}


Now if you cannot/will not do that you must treat this test as an integration test. How about you set up data for it. e.g. insert the row you are wanting to read. Then return the data to its original state. The down side to this is that your test will be slow and brittle.

John Nolan