【问题标题】:How to mock a Model in MVC3 when using Rhino Mocks使用 Rhino Mocks 时如何在 MVC3 中模拟模型
【发布时间】:2011-08-29 20:19:24
【问题描述】:

我是 Rhino Mocks 的新手。我有几个模型。其中之一如下。我想使用 Rhino Mocks。我下载了最新的 Rhino.Mocks.dll 并将其添加到我的测试工具项目中。如何模拟我的模型对象? 我想创建一个单独的项目来模拟我的模型对象。有人可以指导程序吗?

public class BuildRegionModel
{
    public string Name { get; set; }
    public string Description { get; set; }
    public List<SelectListItem> StatusList { get; set; }
    public string Status { get; set; }
    public string ModifyUser { get; set; }
    public DateTime ModifyDate { get; set; }
}

【问题讨论】:

  • 你为什么要模拟你的模型类?您模拟数据访问和服务层等内容,而不是模型类。
  • 不确定您正在创建的测试是什么样的,但您不需要“模拟”模型类。您应该只实例化它们,因为它们只是携带您的数据。如果您正在模拟返回模型实例的控制器依赖项,那么您可以在测试分配部分中使用 dependentService.Stub(ds=&gt;ds.someProcess(0)).IgnoreArguments().Return(new BuildRegionModel {Name="someName"});
  • 那是我的视图模型。我将从尚未准备好的 Web 服务中获取值。所以我必须给它一些假数据。这就是我试图嘲笑它的原因。如果我错了,请让我正确的方式?

标签: asp.net-mvc-3 mocking rhino-mocks


【解决方案1】:

不应嘲笑像这样的视图模型。通常它们通过控制器动作传递给视图,控制器动作将它们作为动作参数。您模拟服务、存储库访问,...

例如,如果您有以下要测试的控制器:

public class HomeController: Controller
{
    private readonly IRegionRepository _repository;
    public HomeController(IRegionRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Show(int id)
    {
        BuildRegionModel model = _repository.GetRegion(id);
        return View(model);
    }
}

您可以在单元测试中模拟 _repository.GetRegion(id) 调用。像这样:

// arrange
var regionRepositoryStub = MockRepository.GenerateStub<IRegionRepository>();
var sut = new HomeController(regionRepositoryStub);
var id = 5;
var buildRegion = new BuildRegionModel
{
    Name = "some name",
    Description = "some description",
    ...
}
regionRepositoryStub.Stub(x => x.GetRegion(id)).Return(buildRegion);

// act
var actual = sut.Show(id);

// assert
var viewResult = actual as ViewResult;
Assert.IsNotNull(viewResult);
Assert.AreEqual(viewResult.Model, buildRegion);

或者对于以视图模型为参数的 POST 控制器操作:

[HttpPost]
public ActionResult Foo(BuildRegion model)
{
    ...
}

在您的单元测试中,您只需准备并实例化一些您将传递给操作的BuildRegion

【讨论】:

    【解决方案2】:

    您不需要模拟您的模型,直接使用它们即可。

    var returnObject = new BuildRegionModel();
    
    mockedObject.Stub(x => x.Method()).Return(returnObject);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多