【发布时间】:2011-07-26 10:56:37
【问题描述】:
我定义了以下单元测试来测试我的模型绑定器:
[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);
}
这是 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);
}
}
在我的模型绑定器中,我调用了一个实用方法,其中包含以下行:
HttpContext.Current.User.Identity.IsAuthenticated
即使我传入用户名,这似乎总是返回 false。我想知道如何修改 GetHttpContext 方法来模拟它。
非常感谢您的帮助。谢谢
【问题讨论】:
标签: asp.net-mvc unit-testing mocking model-binding