簡體   English   中英

如何為ASP.Net MVC偽造UpdateModel?

[英]How do I Fake UpdateModel for ASP.Net MVC?

我正在嘗試對使用UpdateModel的控制器動作進行單元測試,但是我沒有正確模擬HttpContext。 我不斷收到以下異常:

System.InvalidOperationException:先前方法'HttpRequestBase.get_Form();' 需要返回值或引發異常。

為了模擬HttpContext,我正在使用類似於Scott為Rhino模擬發布的東西。

我添加了一種方法來模擬“ HttpRequestBase.get_Form();”

public static void SetupRequestForm(this HttpRequestBase request, NameValueCollection nameValueCollection)
{
    if (nameValueCollection == null)
        throw new ArgumentNullException("nameValueCollection");
    SetupResult.For(request.PathInfo).Return(string.Empty);
    SetupResult.For(request.Form).Return(nameValueCollection);
}

這是單元測試:

[Test]
public void Edit_GivenFormsCollection_CanPersistStyleChanges()
{
    //in memory db setup omitted ...

    var nameValueCollection = new NameValueCollection();
    InitFormCollectionWithSomeChanges(nameValueCollection, style);
    var httpContext = _mock.FakeHttpContext();
    _mock.SetFakeControllerContext(controller, httpContext);
    httpContext.Request.SetupRequestForm(nameValueCollection);

    controller.Edit(1, new FormCollection(nameValueCollection));

    var result = (ViewResult)controller.Edit(1);

    Assert.IsNotNull(result.ViewData);
    style = Style.GetStyle(1);
    AsserThatModelCorrectlyPersisted(style);

}

測試中的控制器動作:

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
    var campaign = Campaign.GetCampaign(id);

    if (campaign == null)
        return View("Error", ViewData["message"] = "Oops, could not find your requested campaign.");
    if (!campaign.CanEdit(User.Identity.Name))
        return View("Error", ViewData["message"] = "You are not authorized to edit this campaign style.");

    var style = campaign.GetStyle();
    //my problem child for tests.
    UpdateModel(style);

    if (!style.IsValid)
    {
        ModelState.AddModelErrors(style.GetRuleViolations());
        return View("Edit", style);
    }

    style.Save(User.Identity.Name);
    return RedirectToAction("Index", "Campaign", new { id });
}

我將接受正確修改我的SetupRequestForm,單元測試的任何答案,或者發布有關如何在MVCContrib項目中使用測試助手來實現相同目標的示例。

您沒有使用傳遞給操作方法的FormCollection。 通常,您通過FormCollection的原因是通過打破對HttpConext的UpdateModel依賴關系來幫助進行測試。

您需要做的就是將UpdateModel行更改為:

UpdateModel(style, collection.ToValueProvider());

完成之后,您就可以忘記設置模擬HttpContext了。 例如,您的測試現在可以顯示為:

[Test]
public void Edit_GivenFormsCollection_CanPersistStyleChanges()
{
    //Blah

    var nameValueCollection = new NameValueCollection();
    InitFormCollectionWithSomeChanges(nameValueCollection, style);
    //Removed stuff

    controller.Edit(1, new FormCollection(nameValueCollection));

    //Blah
}

HTHS,
查爾斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM