c# - 如何模拟这个 MVC Controller

标签 c# asp.net-mvc mocking

我正在使用 Fluent MVC 来测试我的一些 MVC Controller (有些人认为这不是必需的,但这更多的是用于学习过程而不是生产产品)。

界面

public interface ISettings<T> where T : BaseSettingsDto
{
    T GetSettings();
    bool SaveSettings(T model);
}

实现接口(interface)

public class GetSettingsConfiguration : ISettings<FirstSettingsDto>
{
    public FirstSettingsDto GetSettings()
    {
        var repo = new Repository();

        var result = repo.GetAll();
        // Do stuff
        return model;
    }

    public bool SaveSettings(FirstSettingsDto model)
    {
        var repo = new Repository();
        // Do stuff
    }
}

我如何在我的 Controller 中使用它(示例):

[HttpGet]
public ActionResult GetInformation()
{
    var admin = new GetSettingsConfiguration();
    var config = admin.GetSettings();
}

由于接口(interface)使用泛型,我实际上该如何模拟它?

最佳答案

您可以将 ISettings 保存为 Controller 类字段并从构造函数参数初始化它。

public Controller
{

  private ISettings<FirstSettingsDto> _admin;

  public Controller(ISettings<FirstSettingsDto> admin = null)
  {
    _admin = admin ?? new GetSettingsConfiguration();
  }

  [HttpGet]
  public ActionResult GetInformation()
  {
      var config = _admin.GetSettings();
  }
}

现在您可以使用 ISettings 模拟创建 Controller 。

更新:设置ctor参数的默认值(谢谢@JB06)

关于c# - 如何模拟这个 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993466/

相关文章:

c# - 在 C# 中的 TableLayoutPanel 中的面板中居中面板

unit-testing - Grails 2.3.9 和 Spock : How do mock the returns of "where" queries?

c# - 设置 Moq 以忽略虚拟方法

c# - 使用预定义函数检查父目录对请求(URL)的访问

c# - 我可以将 RoutedCommand 绑定(bind)到 WPF 中的命令吗?

c# - 对 Controller 中的所有操作使用 async/await?

asp.net - 错误 500.19 无法读取配置节 'oracle.manageddataaccess.client',因为它缺少节声明

jquery - 将对象列表发布到 MVC 5 Controller

testing - Golang 与 Martini : Mock testing example

c# - 如何保护 WinForms 应用程序内部的 HTTP 流量免受嗅探