How to mock a Model in MVC3 when using Rhino Mocks

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:35:27

问题


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

回答1:


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

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

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

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

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




回答2:


You don't need to mock your models, just use them directly.

var returnObject = new BuildRegionModel();

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


来源:https://stackoverflow.com/questions/7235455/how-to-mock-a-model-in-mvc3-when-using-rhino-mocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!