asp.net-mvc - 如何使用 Moq 对自定义 ModelBinder 进行单元测试?

标签 asp.net-mvc unit-testing moq modelbinders

我在编写一些单元测试来测试我创建的自定义 ModelBinder 时遇到了一些困难。我尝试进行单元测试的 ModelBinder 是我发布的 JsonDictionaryModelBinder here .

我遇到的问题是使用起订量进行模拟所有设置。由于 HttpContextBase 没有被正确模拟,我不断收到 Null 异常。我想。

有人可以帮我找出我没有正确做的事情吗?

这是我试图编写的单元测试示例,但它不起作用:

[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 对象上的第二个 Setup,它会清除原始 Setup,即使您要在对象中“过去”它等级制度。我不确定这是否是起订量中的错误或期望的行为,我以前也遇到过这个问题,但还没有抽出时间来检查它。

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

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

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

关于asp.net-mvc - 如何使用 Moq 对自定义 ModelBinder 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1080997/

相关文章:

css - 非常长的单词不包含在 HTML/CSS 中

asp.net-mvc - 部分 View 的验证总结

c# - 通过 POST 发送字符串 - 不支持的媒体类型或空参数

java - Spring Boot 单元测试 Autowiring

objective-c - 如何使用 OCMock 验证异步方法未在 Objective C 中调用?

c# - 模拟服务提供者 GetServices

asp.net-mvc - 将对象 AJAX 发布到 MVC Controller 会导致所有属性均为 null

unit-testing - 在 espresso 测试中检查按钮是否可点击,android studio

coding-style - FakeItEasy 回调实现

c# - 如何在使用 MOQ 进行模拟时将 Lazy 的类对象类型传递给构造函数