如何使用Moq对自定义ModelBinder进行单元测试?

Chr*_*ann 13 asp.net-mvc unit-testing moq modelbinders

我在编写一些单元测试时遇到了一些困难,无法测试我创建的自定义ModelBinder.我正在尝试单元测试的ModelBinder是我在这里发布的JsonDictionaryModelBinder .

我遇到的问题是使用Moq进行Mocking所有设置.由于HttpContextBase没有被正确模拟,我一直得到Null Exceptions.我认为.

有人能帮我搞清楚我不做的事情吗?

这是我试图编写的单元测试样本不起作用:

[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.");
}
Run Code Online (Sandbox Code Playgroud)

这是上面使用的"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;
    }
}
Run Code Online (Sandbox Code Playgroud)

wom*_*omp 7

罪魁祸首就是这条线:

httpContext.Setup(c => c.Request.RequestType).Returns(
                verbs.ToString().ToUpper()
            );
Run Code Online (Sandbox Code Playgroud)

这在技术上是SetupRequest对象的第二个,它正在消除原始内容Setup,即使你在对象层次结构中"过去"它.我不确定这是Moq中的错误还是期望的行为,我之前也遇到过这个问题而且还没有找到它.

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

request.Setup(c => c.RequestType).Returns(verbs.ToString().ToUpper());
Run Code Online (Sandbox Code Playgroud)

我还注意到你声明的"var u"没有被使用;)