5

我正在为 RC1 中的控制器编写一些单元测试。这是我正在测试的控制器的公共签名:

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AcceptColleague()
    {

AcceptColleague 内部的实现使用 TryUpdateModel(colleague) 方法从表单字段中填充 Colleague 对象。但是,在尝试对该方法进行单元测试时,我在 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(Colleague colleague),然后测试 ModelState.IsValid 属性?

如果是这样,怎么看不到我可以模拟控制器的只读 ModelState 属性的方法?

4

1 回答 1

13

TryUpdateModel 和 ModelState 在 RC 1 中都需要模拟。您唯一需要提供的是 ValueProvider。为此,您可以使用 FormCollection.ToValueProvider()。

您仍然需要模拟您的存储库,但您无需在框架中模拟此功能。试试这个:

    FormCollection fakeForm = new FormCollection();
    fakeForm.Add("ColleagueId", "22222");
    controller.ValueProvider = fakeForm.ToValueProvider();

    // action

注意:不需要模拟的 HttpContext,除非您的代码需要它。

于 2009-02-09T21:53:39.073 回答