Using MBUnit to test values against a database
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. 开发者_如何学JAVAIs there a standard solution to this?
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.
精彩评论