【问题标题】:Verifying File.Delete was called with Moq使用 Moq 调用验证 File.Delete
【发布时间】: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


【解决方案1】:

我是否需要通过将 System.IO.File.Delete 调用包装在我自己的实现接口的类中来进行重构,以便我可以模拟它并验证它是否被调用?

是的

封装实现关注点

public interface IFileSystem {
    void Delete(string path);

    //...code removed for brevity
}

public class ServerFileSystemWrapper : IFileSystem {
    public void Delete(string path) {
        System.IO.File.Delete(Server.MapPath(path));
    }

    //...code removed for brevity
}

这将通过构造函数注入显式注入依赖项并使用。

if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
    _fileSystem.Delete(user.ProfilePictureUrl); //IFileSystem.Delete(string path)

现在可以根据需要设置和验证模拟

//Arrange
var mockFile = new Mock<IFileSystem>();

var profilePictureUrl = "...";

//...code removed for brevity

var sut = new AccountController(mockFile.Object, ....);

//Act
var result = sut.EditProfile(model);

//Assert
result.Should().NotBeNull();
mockFile.Verify(_ => _.Delete(profilePictureUrl), Times.AtLeastOnce());

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2013-01-01
    • 2016-06-12
    相关资源
    最近更新 更多