2008-11-26 120 views

回答

4

您只需創建一個FormCollection的新實例並在其中添加數據。

所以你可以調用這樣的東西而不嘲笑任何東西。

var result = controller.Create(new FormCollection { { "InvoiceId", "-1" } }) as RedirectToRouteResult; 

否則,如果你的代碼調用類似請求或HttpContext的,你可以使用下面的擴展方法(斯科特Hanselman的example啓發)

我使用RhinoMocks。

public static HttpContextBase SetHttpContext(this MockRepository mocks, Controller controller, HttpCookieCollection cookies) { 
cookies = cookies ?? new HttpCookieCollection(); 

var request = mocks.StrictMock<HttpRequestBase>(); 
var context = mocks.StrictMock<HttpContextBase>(); 
var response = mocks.StrictMock<HttpResponseBase>(); 

SetupResult.For(context.Request).Return(request); 
SetupResult.For(context.Response).Return(response); 
SetupResult.For(request.Cookies).Return(cookies); 
SetupResult.For(request.IsSecureConnection).Return(false); 
SetupResult.For(response.Cookies).Return(cookies); 

if (controller != null) 
{ 
    controller.ControllerContext = new ControllerContext(context, new RouteData(), controller); 
} 

if (!string.IsNullOrEmpty(requestUrl)) 
{ 
    request.SetupRequestUrl(requestUrl); 
    SetupResult.For(response.ApplyAppPathModifier(null)).IgnoreArguments().Return(null); 
} 

return context; 
}