中测试操作过滤器

中测试操作过滤器

本文介绍了如何在 ASP.NET MVC 中测试操作过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一些指示.找到 thisthis,但我还是有点困惑.

Need some pointers for this. Found this and this, but I'm still kind a confused.

我只想模拟 ActionExecutedContext,传递它,让过滤器稍微工作并检查结果.

I just want to mock ActionExecutedContext, pass it, let filter to work a bit and check result.

有什么帮助吗?

您可以找到过滤器的来源 这里
(它有所改变,但目前这不是重点).

Source of filter you can find here
(it's changed a bit, but that's not a point at the moment).

所以 - 我想要单元测试,RememberUrl 过滤器足够智能,可以在会话中保存当前 URL.

So - i want unit test, that RememberUrl filter is smart enough to save current URL in session.

推荐答案

1) Mocking Request.Url in ActionExecutedContext:

1) Mocking Request.Url in ActionExecutedContext:

var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.HttpMethod).Returns("GET");
request.SetupGet(r => r.Url).Returns(new Uri("http://somesite/action"));

var httpContext = new Mock<HttpContextBase>();
httpContext.SetupGet(c => c.Request).Returns(request.Object);

var actionExecutedContext = new Mock<ActionExecutedContext>();
actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object);

2) 假设您在 RememberUrlAttribute 的公共构造函数中注入会话包装器.

2) Suppose you are injecting session wrapper in your RememberUrlAttribute's public constructor.

var rememberUrl = new RememberUrlAttribute(yourSessionWrapper);

rememberUrl.OnActionExecuted(actionExecutedContext.Object);

// Then check what is in your SessionWrapper

这篇关于如何在 ASP.NET MVC 中测试操作过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:01