微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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”没有被使用;)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you