【发布时间】:2017-09-14 20:48:23
【问题描述】:
我是单元测试的新手。我正在尝试测试一些非常简单的东西:
[HttpPost]
public ActionResult EditProfile(ProfileViewModel model)
{
if (ModelState.IsValid)
{
// Retrieve current user
var userId = User.Identity.GetUserId();
var user = _dataRepository.GetUserById(userId);
//If it isn't the single-instance default picture, delete the current profile
// picture from the Profile_Pictures folder
if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
System.IO.File.Delete(Server.MapPath(user.ProfilePictureUrl));
在这部分代码中,我创建了一个条件,该行将评估为真:
if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
我想验证是否调用了 System.IO.File.Delete。
最好的方法是什么?
我是否需要通过将System.IO.File.Delete 调用包装在我自己的实现接口的类中来进行重构,以便我可以模拟它并验证它是否被调用?
我正在使用起订量。
【问题讨论】:
-
你最后的说法是绝对正确的。使用允许您模拟它的抽象来封装 IO 调用。
-
谢谢@Nkosi!
-
您也应该对
Service.MapPath执行相同的操作,这些是可以抽象出来的实现问题。实际上,整个语句可以封装在一个抽象中。
标签: c# asp.net-mvc unit-testing moq