gpt4 book ai didi

c# - 如何模拟这个 MVC Controller

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:15 25 4
gpt4 key购买 nike

我正在使用 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 mock 创建 Controller。

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com