如何使用Moq绕过数据层?

时间:2017-08-09 23:32:44

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

我正在学习使用Moq测试我的控制器,但我不确定如何绕过来自控制器的数据层调用。说我有一个像下面这样的方法。我将采用什么方法来测试这样的简单控制器?

[HttpPost]
public ActionResult SomeController(SomeModel model)
{
    if(ModelState.IsValid)
    {
        // Perform some manipulation on modeldata
        model.Value++;

        // Upload Model, Get ID
        model.Id = MyDataLayer.UploadToDb(model);
    }
    return View(model);
}

1 个答案:

答案 0 :(得分:2)

这样的事情:

interface IMyDataLayer 
{
    int UploadToDb(SomeModel model);
}
class MyDataLayer : IMyDataLayer 
{
    public int UploadToDb(SomeModel model)
    {
        // Implementation ...
    }
}
class MyController : Controller
{
    private readonly IMyDataLayer _datalayer;
    public MyController(IMyDataLayer datalayer)
    {
        _datalayer = _datalayer;
    }

    [HttpPost]
    public ActionResult SomeAction(SomeModel model)
    {
        if(ModelState.IsValid)
        {
            // Perform some manipulation on modeldata
            model.Value++;

            // Upload Model, Get ID
            model.Id = _datalayer.UploadToDb(model);
        }
        return View(model);
    }
}

然后您可以使用Moq创建IMyDataLayer的模拟。