asp.net-mvc – 如何使用Moq测试一个自定义的ModelBinder?

我在编写一些单元测试时遇到困难,以测试我创建的自定义ModelBinder.我试图单元测试的ModelBinder是我发布了 here的JsonDictionaryModelBinder.

我遇到的问题是使用Moq获取所有的Mocking设置.由于HttpContextBase没有被正确地模拟,所以我不断得到空的异常.我认为.

有人能帮我弄清楚我没有做什么相关的事情吗?

以下是单元测试的示例我正在尝试写入不起作用:

[TestMethod()]
public void BindModeltest()
{
    JsonDictionaryModelBinder target = new JsonDictionaryModelBinder();

    NameValueCollection nameValueCollection = new NameValueCollection() {
        {"First","1"},{"Second","2"},{"Name","Chris"},{"jsonValues","{id: 200,name: 'Chris'}"}
    };

    HttpContextBase httpContext = MockHelper.FakeHttpContext(HttpVerbs.Post,nameValueCollection);

    ControllerContext controllerContext =
        new ControllerContext(new RequestContext(httpContext,new RouteData()),new Mock<Controller>().Object);


    Predicate<string> predicate = propertyName => (propertyName == "jsonValues");
    ModelBindingContext bindingContext = new ModelBindingContext()
    {
        Model = null,ModelType = typeof(JsonDictionary),ModelState = new ModelStateDictionary(),PropertyFilter = predicate,ValueProvider = new Dictionary<string,ValueProviderResult>() { { "foo",null } }
    };

    //object expected = null; // Todo: Initialize to an appropriate value
    var actual = target.BindModel(controllerContext,bindingContext) as JsonDictionary;

    Assert.IsNotNull(actual);

    Assert.AreEqual("Chris",actual["name"]);
    //Assert.AreEqual(expected,actual);
    Assert.Inconclusive("Verify the correctness of this test method.");
}

这是上面使用的“FakeHttpContext”方法

public static class MockHelper
{
    public static HttpContextBase FakeHttpContext(HttpVerbs verbs,NameValueCollection nameValueCollection)
    {
        var httpContext = new Mock<HttpContextBase>();

        var request = new Mock<HttpRequestBase>();
        request.Setup(c => c.Form).Returns(nameValueCollection);
        request.Setup(c => c.QueryString).Returns(nameValueCollection);

        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();
        httpContext.Setup(c => c.Request).Returns(request.Object);

        var u = verbs.ToString().toupper();
        httpContext.Setup(c => c.Request.RequestType).Returns(
            verbs.ToString().toupper()
        );

        httpContext.Setup(c => c.Response).Returns(response.Object);
        httpContext.Setup(c => c.Server).Returns(server.Object);
        httpContext.Setup(c => c.User.Identity.Name).Returns("testclient");
        return httpContext.Object;
    }
}

解决方法

罪魁祸首是这一行:
httpContext.Setup(c => c.Request.RequestType).Returns(
                verbs.ToString().toupper()
            );

这在技术上是Request对象上的第二个安装程序,它正在擦除原始的安装程序,即使您要在对象层次结构中“过去”.我不知道这是否是Moq或所需行为的错误,我以前也遇到过,并没有得到检查.

您可以通过将该行移动到上面设置您的请求并直接设置,而不是通过httpContext来解决.所以,

request.Setup(c => c.RequestType).Returns(verbs.ToString().toupper());

我也注意到你声明的“var u”没有被使用;)

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...