how would I mock a querystring

2019-04-25 05:42发布

问题:

using the following in Moq

public Mock<HttpRequestBase> Request { get; set; }

how can I mock this Request[....]

(in controller)
var modelFromPost = Request["mymodel"]

here's what I have so far

public class ContextMocks
{

    public Mock<HttpContextBase> HttpContext { get; set; }
    public Mock<HttpRequestBase> Request { get; set; }
    public RouteData RouteData { get; set; }


    public ContextMocks(Controller controller)
    {
        HttpContext = new Mock<HttpContextBase>();
        HttpContext.Setup(x => x.Request).Returns(Request.Object);

    }

}

cheers!

回答1:

You can mock indexers with the SetupGet method:

ContextMocks.Request.SetupGet(r => r["mymodel"]).Returns(myModel);