我在學習如何做單元測試和嘲弄。我理解TDD和基本測試的一些原則。但是,我正在考慮重構下面沒有測試編寫的代碼,並試圖瞭解它需要如何更改以使其可測試。我怎樣才能重構這個工廠類型的方法和數據庫調用是可測試的?
public class AgentRepository
{
public Agent Select(int agentId)
{
Agent tmp = null;
using (IDataReader agentInformation = GetAgentFromDatabase(agentId))
{
if (agentInformation.Read())
{
tmp = new Agent();
tmp.AgentId = int.Parse(agentInformation["AgentId"].ToString());
tmp.FirstName = agentInformation["FirstName"].ToString();
tmp.LastName = agentInformation["LastName"].ToString();
tmp.Address1 = agentInformation["Address1"].ToString();
tmp.Address2 = agentInformation["Address2"].ToString();
tmp.City = agentInformation["City"].ToString();
tmp.State = agentInformation["State"].ToString();
tmp.PostalCode = agentInformation["PostalCode"].ToString();
tmp.PhoneNumber = agentInformation["PhoneNumber"].ToString();
}
}
return tmp;
}
private IDataReader GetAgentFromDatabase(int agentId)
{
SqlCommand cmd = new SqlCommand("SelectAgentById");
cmd.CommandType = CommandType.StoredProcedure;
SqlDatabase sqlDb = new SqlDatabase("MyConnectionString");
sqlDb.AddInParameter(cmd, "AgentId", DbType.Int32, agentId);
return sqlDb.ExecuteReader(cmd);
}
}
這兩個方法在一個類中。 GetAgentFromDatabase中與數據庫相關的代碼與企業庫相關。
我該如何去做這個測試?我應該將GetAgentFromDatabase方法抽象爲不同的類嗎? GetAgentFromDatabase是否應該返回IDataReader以外的內容?任何建議或指向外部鏈接將不勝感激。