我想用C#为我的add方法编写单元测试。我的方法得到一个狗实体和类型作为参数。这个方法通过我的服务将它添加到数据库中。
public async Task<ActionResult> Add(Dog dog, string type)
{
if (ModelState.IsValid)
{
var d = new Dog();
d.Name = dog.Name;
d.NumOfLegs = dog.NumOfLegs;
d.BirthdayDate = dog.BirthdayDate;
if(type == "mom"){
//when the dog is a mom, dog.Childrens got default puppies
InitChildrenOfMomDog(dog);
}
dogService.Insert(dog);
return RedirectToAction("Home");
}
return View(dog);
}我想签入单元测试,我的方法正确工作,默认的小狗添加到狗,或者如果用户添加了有效(或不)属性.我在这一点上有点困惑。
发布于 2017-12-03 20:33:35
您应该将Controller的代码重构为一个单独的视图模型类。这允许直接测试视图模型,而无需与MVC框架交互。查看MVVM模式。
Controller创建、构建和返回视图模型类.只有特定于视图的逻辑才应该出现在这里(如果有的话),因为它不会直接测试。
ViewModel执行视图的所有逻辑操作,例如数据库查询。可以直接测试。
代码示例
控制器
public async Task<ActionResult> Add(Dog dog, string type)
{
if (!ModelState.IsValid)
return View(dog);
var vm = new AddDogVM(dogService);
vm.Add(dog, type);
return RedirectToAction("Home");
}视图模型类
public class AddDogVM
{
private IDogService _dogService
public AddDogVM(IDogService dogService)
{
_dogService = dogService;
}
public async Task<ActionResult> Add(Dog dog, string type)
{
var d = new Dog();
d.Name = dog.Name;
d.NumOfLegs = dog.NumOfLegs;
d.BirthdayDate = dog.BirthdayDate;
if (type == "mom") {
InitChildrenOfMomDog(dog);
}
_dogService.Insert(dog);
}
}测试
public void Test()
{
var dogService = SomeMockingFramework.CreateSubstituteFor<IDogService>();
var vm = new AddDogVM(dogService);
vm.Add(...);
// Assertions
}https://stackoverflow.com/questions/47622764
复制相似问题