我正在为RC1中的控制器编写一些单元测试。这里是 控制器的公共签名我正在测试:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AcceptColleague()
{
AcceptColleague中的实现使用从表单字段填充Colleague对象的TryUpdateModel(同事)方法。但是,在尝试对方法进行单元测试时,我在TryUpdateModel行上遇到“未设置为对象实例的对象引用”错误。
这是我的单元测试代码:
// definition
HomeController controller = new HomeController();
IColleagueRepository fakeColleagueRepo = MockRepository.GenerateMock<IColleagueRepository>();
Colleague requestedColleauge = new Colleague();
EmployeeInfo currentUser = new EmployeeInfo();
HttpContextBase fakeHttpContext = MockRepository.GenerateMock<HttpContextBase>();
HttpRequestBase fakeHttpRequest = MockRepository.GenerateMock<HttpRequestBase>();
ControllerContext fakeContext = MockRepository.GenerateMock<ControllerContext>(fakeHttpContext, new RouteData(), controller);
NameValueCollection fakeForm = new NameValueCollection();
// expectations
fakeColleagueRepo.Expect(c => c.Read(1234)).Return(requestedColleauge);
fakeColleagueRepo.Expect(c => c.Update(requestedColleauge));
fakeColleagueRepo.Expect(c => c.Add(new Colleague())).IgnoreArguments().Constraints(Is.NotNull());
fakeContext.Expect(cx => cx.HttpContext).Return(fakeHttpContext);
fakeHttpContext.Expect(hcx => hcx.Request).Return(fakeHttpRequest);
fakeHttpRequest.Expect(hr => hr.Form).Return(fakeForm);
// setup
controller.ColleagueRepository = fakeColleagueRepo;
controller.ControllerContext = fakeContext;
requestedColleauge.TargetEmployeeInfoId = 123456;
requestedColleauge.GeneratedEmployeeInfoId = 654321;
currentUser.EmployeeInfoId = 123456;
fakeForm.Add("ColleagueId", "22222");
// action
RedirectToRouteResult result = controller.AcceptColleague() as RedirectToRouteResult;
// validation
Assert.IsNotNull(result, "AcceptColleague() did not return RedirectToRouteResult");
我是否在模拟上遗漏了某些内容,或者我应该使用像AcceptColleague(同事同事)这样的不同公共签名,然后测试ModelState.IsValid属性?
如果是这样,怎么看不到我可以从控制器模拟只读ModelState属性的方法呢?
答案 0 :(得分:13)
TryUpdateModel和ModelState都需要RC 1中的零模拟。您唯一需要提供的是ValueProvider。为此,您可以使用FormCollection.ToValueProvider()。
您仍然需要模拟您的存储库,但是您无需在框架中模拟此功能。试试这个:
FormCollection fakeForm = new FormCollection();
fakeForm.Add("ColleagueId", "22222");
controller.ValueProvider = fakeForm.ToValueProvider();
// action
注意:除非你的代码需要,否则不需要模拟的HttpContext。