How to mock a Model in MVC3 when using Rhino Mocks
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 st开发者_StackOverflowring 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);
}
}
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.
You don't need to mock your models, just use them directly.
var returnObject = new BuildRegionModel();
mockedObject.Stub(x => x.Method()).Return(returnObject);
精彩评论