当用Moq模拟HttpApplicationState时,似乎不能设置对象
本文关键字:不能 设置 对象 Moq 模拟 HttpApplicationState 当用 | 更新日期: 2023-09-27 18:07:01
我有一个动作过滤器,它在过滤器上下文的HttpContext的HttpApplicationState中设置一个对象。我想在单元测试中具有此功能,但由于某种原因,对象没有在底层NameObjectCollectionBase中设置,HttpApplicationState从中派生。
我知道这个功能是有效的,因为当我运行MVC应用程序时,它按预期工作。
我如何设置我的测试,让它设置对象在应用程序状态?我使用Moq,这里是一些代码到目前为止。
失败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"]);
}
看起来您希望您的模拟对象或多或少地像真实对象一样。事实并非如此;mock只会做你让它做的事,不多也不少。如果在调用时不告诉mock返回特定的内容…
context.HttpContext.Application["config"]
…那么它就不会。如果您确实设置了mock来返回特定的内容,那么它将破坏测试的目的。
没有任何额外的理解或您的情况(测试策略的"什么"answers"为什么"),看起来您正在尝试确保调用应用程序状态上的设置。我建议使用mockApplicationState.Verify()
作为断言来测试是否发生,而不是测试对象本身的结果状态。
Verify()允许您断言/确保调用了一个方法(或属性方法),无论是否有条件。这应该可以让你开始:
http://code.google.com/p/moq/wiki/QuickStart验证
所以你的验证看起来像这样(完全未经测试!):
mockApplicationState.Verify(x => x["config"] == [expected value], Times.Once());
这基本上表示如果mockApplicationState["config"]被设置为期望值少于一次或多于一次,则测试失败。
我假设HttpApplicationStateBase不是密封的。
作为MOQ的替代方案,我经常在这种情况下生成一些从System.Web.Abstractions中的基类派生的存根。我经常在MVC应用程序中使用这种技术,因为MVC/WebApi控制器包含对HttpContext (HttpContextBase)的抽象
这样我可以在我的单元/集成测试中存根HttpContext需求,这里有一个示例…
public class MockHttpApplicationState : HttpApplicationStateBase
{
private IDictionary<string, object> _appState = new Dictionary<string, object>();
public override void Add(string name, object value)
{
_appState.Add(name, value);
}
public override object Get(string name)
{
return _appState[name];
}
public override object this[string name]
{
get
{
return _appState[name];
}
set
{
_appState[name] = value;
}
}
}
public class MockHttpContext : HttpContextBase
{
private IDictionary<string, object> _appKeys;
public MockHttpContext()
{
}
/// <summary>
/// Accepts a dictionary of app keys to supply to the HttpApplicationState instance
/// </summary>
/// <param name="applicationState"></param>
public MockHttpContext(IDictionary<string,object> applicationState)
{
_appKeys = applicationState;
}
public override Cache Cache
{
get
{
return HttpRuntime.Cache;
}
}
public override HttpApplicationStateBase Application
{
get
{
var mockAppState = new MockHttpApplicationState();
foreach (string key in _appKeys.Keys)
{
mockAppState.Add(key, _appKeys[key]);
}
return mockAppState;
}
}
public override HttpRequestBase Request
{
get
{
return new HttpRequestWrapper(new HttpRequest(null,"http://localhost",null));
}
}
}
然后我的测试可以建立控制器和Http上下文:
private readonly OnlineShop.MVC.Controllers.HomeController _controller =
new MVC.Controllers.HomeController(null,new UnitOfWork());
[OneTimeSetUp]
public void Init()
{
var appKeys = new Dictionary<string, object>();
appKeys.Add("localhost", 1);
var httpContext = new MockHttpContext(appKeys);
_controller.ControllerContext = new ControllerContext()
{
Controller = _controller,
RequestContext = new RequestContext(httpContext, new RouteData())
};
}
[Test]
public void Index_Returns_HomeView()
{
var view = _controller.Index() as ViewResult;
var viewModel = view.Model as MVC.ViewModels.Home;
Assert.IsInstanceOf<OnlineShop.MVC.ViewModels.Home>(viewModel);
Assert.IsTrue(viewModel.FeaturedProducts.Count > 0);
}
我的控制器意识到它的环境HttpContextBase实例提供缓存和应用程序状态:
public ActionResult Index()
{
string cacheKey = string.Format("FeaturedProducts-{0}",WebsiteId);
IList<Product> productList = this.HttpContext.Cache[cacheKey] as IList<Product>;
//My app keeps a list of website contexts in the Application. This test returns 1 based on the unit / int tests or a real world db value when hosted on IIS etc..
int websiteId = (int)HttpContext.Application[this.Request.Url.Host];