c# - 验证 File.Delete 是否已使用 Moq 调用

标签 c# asp.net-mvc unit-testing moq

我是单元测试新手。我正在尝试测试一些非常简单的东西:

[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));

在这部分代码中,我创建了一个条件,该行将计算为 true:

if (!String.Equals(user.ProfilePictureUrl, _defaultPic))

我想验证是否调用了System.IO.File.Delete

执行此操作的最佳方法是什么?

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

我正在使用起订量。

最佳答案

Do I need to refactor by wrapping the System.IO.File.Delete call in my own class that implements an interface so that I can mock it and verify that it was called?

是的

封装实现问题

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
}

它将通过构造函数注入(inject)显式注入(inject)到依赖项中并使用。

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());

关于c# - 验证 File.Delete 是否已使用 Moq 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46227992/

相关文章:

c# - 如何在 TextBox 中保存用户输入的值? (WPF, XAML)

jquery - 如何构建 Web 应用程序以使 AJAX 和 DHTML 更容易?

c# - 使用 LINQ 进行 Orderby 和 thenby

reactjs - 如何使用 Jest 和 Enzyme 模拟 React 无状态柯里化(Currying)函数

database - flask create_app 和 setUp unittest

java - 是否有等效的 verifyZeroInteractions() 用于验证与模拟对象交互的确切数量?

c# - 将字符串计算为 C# 中的属性

c# - 使用请求 header 对 BasicHttpBinding 进行身份验证

javascript - 通过调用函数自动更新站点

c# - 在 mvc 应用程序中发送电子邮件时遇到问题