单元测试自定义模型绑定器 - 假 HttpContext 问题

nfp*_*lee 5 asp.net-mvc unit-testing mocking model-binding

我定义了以下单元测试来测试我的模型绑定器:

[TestMethod]
public void DateTime_Works() {
    // Arrange
    var controllerContext = FakeContext.GetAuthenticatedControllerContext(new Mock<Controller>().Object, "TestAdmin");

    var values = new NameValueCollection {
        { "Foo.Date", "12/02/1964" },
        { "Foo.Hour", "12" },
        { "Foo.Minute", "00" },
        { "Foo.Second", "00" }
    };

    var bindingContext = new ModelBindingContext() { ModelName = "Foo", ValueProvider = new NameValueCollectionValueProvider(values, null) };
    var binder = new DateAndTimeModelBinder();

    // Act
    var result = (DateTime)binder.BindModel(controllerContext, bindingContext);

    // Assert
    Assert.AreEqual(DateTime.Parse("1964-12-02 12:00:00"), result);
}
Run Code Online (Sandbox Code Playgroud)

这是 FakeContext 类:

public static class FakeContext {
    public static HttpContextBase GetHttpContext(string username) {
        var context = new Mock<HttpContextBase>();
        context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));

        return context.Object;
    }

    public static ControllerContext GetControllerContext(Controller controller) {
        return GetAuthenticatedControllerContext(controller, null);
    }

    public static ControllerContext GetAuthenticatedControllerContext(Controller controller, string username) {
        var httpContext = GetHttpContext(username);
        return new ControllerContext(httpContext, new RouteData(), controller);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的模型绑定器中,我调用了一个实用程序方法,其中包含以下行:

HttpContext.Current.User.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

即使我传入用户名,这似乎总是返回 false。我想知道如何修改 GetHttpContext 方法来模拟这一点。

我很感激你的帮助。谢谢

Bri*_*haw 2

您正在模拟请求的 IsAuthenticated 属性,而不是用户身份的属性。你的mock表明请求已通过身份验证,但与身份验证无关。

稍微改变一下你的模型应该可以解决你的问题。

var identityMock = new Mock<IIdentity>();
identityMock.SetupGet( i => i.IsAuthenticated ).Returns( !string.IsNullOrEmpty(username));

var userMock = new Mock<IPrincipal>();
userMock.SetupGet( u => u.Identity ). Returns( identityMock.Object );

var context = new Mock<HttpContextBase>();
context.SetupGet( ctx => ctx.User ).Returns( userMock.Object );
Run Code Online (Sandbox Code Playgroud)

编辑我想得越多,我就越觉得这些模拟需要单独设置

注意,我没有执行这段代码。不过,它应该可以满足您的需求。

MSDN for Request.IsAuthenticated http://msdn.microsoft.com/en-us/library/system.web.httprequest.isauthenticated.aspx

MSDN User.Identity.IsAuthenticated http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.isauthenticated.aspx

希望这可以帮助。