你應該提取代碼,這使得數據庫調用轉換爲單獨的對象(取Single Responsibility Principle看看)。例如。你必須控制
public class PersonController : Controller
{
public ActionResult Index()
{
var connectionString =
ConfigurationManager.ConnectionStrings["foo"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
string sql = "SELECT Name FROM People";
var command = connection.CreateCommand(sql);
var reader = command.ExecuteReader();
List<Person> people = new List<Person>();
while(reader.Read())
{
Person p = new Person();
p.Name = reader["Name"].ToString();
people.Add(p);
}
return View(people);
}
}
}
提取數據訪問代碼放到單獨的類(通常這樣叫repositories類):
public class PersonRepository : IPersonRepository
{
public List<Person> GetAllPeople()
{
var connectionString =
ConfigurationManager.ConnectionStrings["foo"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
string sql = "SELECT Name FROM People";
var command = connection.CreateCommand(sql);
var reader = command.ExecuteReader();
List<Person> people = new List<Person>();
while(reader.Read())
{
Person p = new Person();
p.Name = reader["Name"].ToString();
people.Add(p);
}
return people;
}
}
}
正如你已經通知我宣佈抽象是由數據訪問類實現:
public interface IPersonRepository
{
List<Person> GetAllPeople();
// other data access API will go here
}
使控制器依賴於這種抽象(這很重要 - 抽象很容易模擬):
public class PersonController : Controller
{
private IPersonRepository _personRepository;
public PersonController(IPersonRepository personRepository)
{
_personRepository = personRepository;
}
public ActionResult Index()
{
var people = _personRepository.GetAllPeople();
return View(people);
}
}
然後注入倉庫實現到控制器(Dependency Injection in .NET),並嘲笑它的測試:
var repositoryMock = new Mock<IPersonRepository>();
var people = new List<People>(); // provide some sample list
repositoryMock.Setup(r => r.GetAllPeople()).Return(people);
var controller = new PersonController(repositoryMock.Object);
var result = (ViewResult)controller.Index();
// Assert here
Assert.AreEqual(result.ViewName, "Index");
Assert.AreEqual(result.Model, people);
repositoryMock.VerifyAll();
@ lazyberezovsky..can請你給我一個樣品測試方法 –
@Avinash是,已經添加 –
@ layberezovsky..Super example..Thank你這麼多.. –