我不會讓該類靜態,而是使用依賴注入並將所需資源傳遞給該類。這樣你可以創建一個模擬庫(實現IRepository接口)來測試。如果您將該類設爲靜態,並且不會傳入您的存儲庫,那麼測試起來非常困難,因爲您無法控制靜態類所連接的內容。
注意:下面的代碼是一個粗略的例子,只是爲了傳達一點,不一定要編譯和執行。
public interface IRepository
{
public DataSet ExecuteQuery(string aQuery);
//Other methods to interact with the DB (such as update or insert) are defined here.
}
public class CompanyInfoManager
{
private IRepository theRepository;
public CompanyInfoManager(IRepository aRepository)
{
//A repository is required so that we always know what
//we are talking to.
theRepository = aRepository;
}
public List<string> GetCompanyNames()
{
//Query database and return list of company names
string query = "SELECT * FROM COMPANIES";
DataSet results = theRepository.ExecuteQuery(query);
//Process the results...
return listOfNames;
}
}
測試CompanyInfoManager:
//Class to test CompanyInfoManager
public class MockRepository : IRepository
{
//This method will always return a known value.
public DataSet ExecuteQuery(string aQuery)
{
DataSet returnResults = new DataSet();
//Fill the data set with known values...
return returnResults;
}
}
//This will always contain known values that you can test.
IList<string> names = new CompanyInfoManager(new MockRepository()).GetCompanyNames();
我不想羅嗦了大約依賴注入。 Misko Hevery's blog詳細瞭解great post to get started。
謝謝大腦。我有類似於你的例子的東西。我給出的示例代碼是我的課程的一個超級精簡版本。是的,我也喜歡Repository模式。另外,我使用CastleWindsor作爲我的DI容器。 – sean717 2010-07-14 22:53:04