我已经阅读了越来越多有关单元测试的内容,并决心将其付诸实践。我使用存储库模式、依赖注入和 EF 挖出了一个用 ASP.NET MVC 编写的项目。我的第一个任务是对控制器进行单元测试。这是控制器中要测试的片段:
IUserRepository _userRepository;
IAttachmentRepository _attachmentRepository;
IPeopleRepository _peopleRepository;
ICountryRepository _countryRepository;
public UserController(IUserRepository userRepo, IAttachmentRepository attachRepo, IPeopleRepository peopleRepo, ICountryRepository countryRepo)
{
_userRepository = userRepo;
_attachmentRepository = attachRepo;
_peopleRepository = peopleRepo;
_countryRepository = countryRepo;
}
public ActionResult Details()
{
UserDetailsModel model = new UserDetailsModel();
foreach (var doc in _attachmentRepository.GetPersonAttachments(Globals.UserID))
{
DocumentItemModel item = new DocumentItemModel();
item.AttachmentID = doc.ID;
item.DocumentIcon = AttachmentHelper.GetIconFromFileName(doc.StoragePath);
item.DocumentName = doc.DocumentName;
item.UploadedBy = string.Format("{0} {1}", doc.Forename, doc.Surname);
item.Version = doc.VersionID;
model.Documents.Add(item);
}
var person = _peopleRepository.GetPerson();
var address = _peopleRepository.GetAddress();
model.PersonModel.DateOfBirth = person.DateOfBirth;
model.PersonModel.Forename = person.Forename;
model.PersonModel.Surname = person.Surname;
model.PersonModel.Title = person.Title;
model.AddressModel.AddressLine1 = address.AddressLine1;
model.AddressModel.AddressLine2 = address.AddressLine2;
model.AddressModel.City = address.City;
model.AddressModel.County = address.County;
model.AddressModel.Postcode = address.Postcode;
model.AddressModel.Telephone = address.Telephone;
model.DocumentModel.EntityType = 1;
model.DocumentModel.ID = Globals.UserID;
model.DocumentModel.NewFile = true;
var countries = _countryRepository.GetCountries();
model.AddressModel.Countries = countries.ToSelectListItem(1, c => c.ID, c => c.CountryName, c => c.CountryName, c => c.ID.ToString());
return View(model);
}
我想测试 Details 方法并有以下查询:
1) Globals.UserID 属性从会话对象中检索当前用户。我怎样才能轻松测试这个(我正在使用内置的 VS2010 单元测试和起订量)
2) 我在这里调用 AttachmentHelper.GetIconFromFileName() ,它只是查看文件的扩展名并显示一个图标。我还在附件存储库中调用 GetPersonAttachments,调用 GetPerson、GetAddress 和 GetCountries 以及调用创建的扩展方法将 List 转换为 SelectListItem 的 IEnumerable。
此控制器操作是不良做法的示例吗?它使用了大量的存储库和其他辅助方法。据我所知,对这个单一动作进行单元测试将需要大量代码。这会适得其反吗?
在测试项目中对一个简单的控制器进行单元测试是一回事,但是当你进入像这样的现实生活中的代码时,它可能会变成一个怪物。
我想我的问题真的是我应该重构我的代码以使其更容易测试,还是我的测试应该变得更加复杂以满足当前代码?