使用Rhino Mocks时如何在MVC3中模拟模型 [英] How to mock a Model in MVC3 when using Rhino Mocks

查看:59
本文介绍了使用Rhino Mocks时如何在MVC3中模拟模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Rhino Mocks. I have several models. One of them is as below. I want to use Rhino Mocks. I downloaded the latest Rhino.Mocks.dll and added it to my testharness project. How do I mock my model objects? I want to create a seperate project for mocking my model object. Can someone guideme the procedure?

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; }
}

推荐答案

不应模仿这种视图模型.通常,它们由控制器动作传递给视图,并且控制器动作将其作为动作参数.您嘲笑服务,存储库访问等等...

View models like this one should not be mocked. Usually they are passed to views by controller actions and controller actions take them as action arguments. You mock services, repository accesses, ...

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

So for example if you have the following controller that you want to test:

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)调用.像这样:

you could mock the _repository.GetRegion(id) call in your unit test. Like this:

// 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控制器动作:

or for a POST controller action which takes a view model as argument:

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

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

in your unit test you would simply prepare and instantiate some BuildRegion that you would pass to the action.

这篇关于使用Rhino Mocks时如何在MVC3中模拟模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆