簡體   English   中英

單元測試asp.net mvc restful routing FormatResult

[英]Unit testing asp.net mvc restful routing FormatResult

我正在為asp.net mvc使用restful routing模塊 ,並且非常滿意。 但我不能得到一件事。 例如,我有一個像這樣的控制器動作:

public ActionResult Index()
{
    if (Request.IsAjaxRequest()) 
        return PartialView();
    return View();
}

編寫這樣的規范沒問題:

[Subject(typeof(LotsController))]
public class When_Index_called
{
    static LotsController controller;

    static ActionResult actionResult;

    Establish context = () => {
        controller = mocker.Create<LotsController>();
        controller.ControllerContext = Contexts.Controller.Default;
    };

    Because of = () => actionResult = controller.Index();

    It should_render_view = () => actionResult.AssertViewRendered().ForViewWithDefaultName();

但是使用休息時,我希望有一個像這樣的Index方法:

public ActionResult Index()
{
    return RespondTo(format => {
        format.Html = () => {
            if (Request.IsAjaxRequest()) 
                return PartialView();
            return View();
        };
        format.Json = () => Json(new { });
    });
}

確定以前的規范失敗了,因為動作結果不是ViewResult類型,它的類型是FormatResult。 FormatResult本身會覆蓋返回void的ExecuteResult方法。 如果我想在FormatResult中驗證操作結果類型和數據,我該如何對這種情況進行單元測試?

在將來版本的restful routing中,這樣的代碼是可能的:

var formatResult = actionResult as FormatResult;
ActionResult result = formatResult.ExposeResult().Html();
result.ShouldBeOfType<ViewResult>();

可以斷言使用返回的視圖的名稱嗎?

這不會給你格式,但會讓你測試返回的視圖。

這取決於ActionResult使用的請求。 這個邏輯在FormatResult的ExecuteResult方法運行時發生。 解決這個問題的最好方法是重構FormatResult類,這樣就可以在不執行它的情況下獲取所選的ActionResult。 拉請求歡迎:)

目前唯一可行的方法是運行ExecuteResult方法並檢查結果。

暫無
暫無

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

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