我有一个动作过滤器,它在过滤器上下文的 HttpContext 的 HttpApplicationState 中设置一个对象。我希望在单元测试中具有此功能,但由于某种原因,该对象未在 HttpApplicationState 派生的基础 NameObjectCollectionBase 中设置。
我知道该功能有效,因为当我运行 MVC 应用程序时,它按预期工作。
如何设置我的测试以使其在应用程序状态下设置对象?我使用的是起订量,这里是到目前为止的一些代码。它失败了
Asset.IsNotNull(context.HttpContext.Application["config"]);
这是代码。
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ControllerBase controller = filterContext.Controller;
if (!(controller is ApplicationController))
return;
ApplicationController applicationController = (ApplicationController) controller;
IDictionary<string, string> config;
// Loads the view configuration values.
if (filterContext.HttpContext.Application["config"] == null)
{
config = applicationController.ApplicationService.GetConfiguration();
filterContext.HttpContext.Application["config"] = config;
}
else
{
config = (IDictionary<string, string>) filterContext.HttpContext.Application["config"];
}
applicationController.ViewBag.BlogTitle = AddConfigurationValueToViewBag("BlogTitle", config);
}
这是到目前为止的测试。
[TestMethod]
public void ApplicationAttribute_OnActionExecuted_SetsConfigurationDctionaryInAppicationCache()
{
// Arrange
Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();
var mockApplicationState = new Mock<HttpApplicationStateBase>();
httpContext.Setup(h => h.Application).Returns(mockApplicationState.Object);
ApplicationController applicationController = new BlogController(null, null, MocksAndStubs.CreateMockApplicationService());
Mock<ActionExecutedContext> actionExecutedContext = new Mock<ActionExecutedContext>();
actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object);
actionExecutedContext.SetupGet(c => c.Controller).Returns(applicationController);
// Act
ApplicationAttribute applicationAttribute = new ApplicationAttribute();
ActionExecutedContext context = actionExecutedContext.Object;
applicationAttribute.OnActionExecuted(context);
// Assert
Assert.IsNotNull(context.HttpContext.Application["config"]);
}