Say I have a controller which looks something like the one below where I fetch some items out of a database and add them to a paged list. How would I go about writing a unit test for this? I can't seem to find any good material on this.
Controller:
public class ErrorController : Controller
{
public ErrorModel Errors { get; set; }
public List<ErrorModel> ErrorList { get; set; }
public ActionResult Error(int? page)
{
string cs = "Data Source=" + "some\\path";
using (SQLiteConnection con = new SQLiteConnection(cs))
{
var listOfErrors = new List<ErrorModel>();
string stm = "SELECT * FROM Error WHERE Checked == 'False'";
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listOfErrors.Add(new ErrorModel
{
Id = rdr["ID"].ToString(),
Type = rdr["Type"].ToString(),
});
}
rdr.Close();
ErrorList = listOfErrors;
}
}
con.Close();
}
// stuff for paging
int pageSize = 10;
int pageNumber = (page ?? 1); // if there is no page, return page 1
return View(ErrorList.ToPagedList(pageNumber, pageSize));
}
My current, obviously not adequate unit test:
[TestClass]
public class ErrorControllerTest
{
[TestMethod]
public void TestErrorView()
{
var controller = new ErrorController();
var result = controller.Error(1) as ViewResult;
Assert.AreEqual("Error", result.ViewName);
}
}
Any hints greatly appreciated.
答案 0 :(得分:1)
你想测试什么?数据库结果?控制器动作?
如果您认真考虑尝试对此进行测试,那么您可能会更加幸运地抽象出您的数据检索/业务逻辑和单独测试,而不依赖于MVC操作。如果您的业务方法正在执行它(根据测试)您不需要测试MVC将返回结果。
public ActionResult Error(int? page)
{
var model = _privateObjForReturningStuff.GetPage(page);
return View(model);
}
public class ForReturningStuff
{
public Model GetPage(int page)
{
... gets page stuff
}
}
[TestClass]
public class ForReturningStuffTest
{
[TestMethod]
public void GetPage_does_something_I_can_assert()
{
...
}
}
通常,您不会对第三方代码进行单元测试。