我正在使用 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/