如何为 mvc 动作过滤器编写测试用例?

发布于 2024-08-14 03:01:13 字数 360 浏览 3 评论 0原文

我有一个从下面的链接获得的动作过滤器 http://blog.wekeroad.com/blog/aspnet -mvc-secure-your-controller-actions/

有一个叫做“RequiresAuthenticationAttribute”的东西 为此我需要编写测试用例。 我该怎么做?从我读到的一些博客来看,我们需要模拟 httcontext。 我怎么能嘲笑这个呢?我需要办理什么手续?有这方面的链接吗?

I have an action filter which i got from the below link
http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/

there is something called "RequiresAuthenticationAttribute"
for this i need to write test case.
how can i do this? form some of the blogs i read that we need to mock httcontext.
How can i mock this? what is the procedure that i need to do? is there any link for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最初的梦 2024-08-21 03:01:13

不要使用 Rob 博客中的 [RequiresAuthentication] 属性。它适用于非常旧的 MVC 预发行版本。请改用内置的 [Authorize] 属性。

由于 [Authorize] 属性是由 MVC 团队编写的,因此您不需要对其逻辑进行单元测试。但是,如果您愿意,您可以验证它是否已应用于您的控制器或操作。只需获取您感兴趣的 Type 或 MethodInfo,然后调用其 GetCustomAttributes() 方法即可获取 AuthorizeAttribute 的实例。您可以检查这些实例是否有您期望的值。

如果需要,您可以查看 AuthorizeAttribute 的源代码有关编写您自己的过滤器的信息。此外,您可以查看这种类型的官方单元测试,因此,如果您最终编写了一个过滤器,您可以使用类似的方法来编写您自己类型的单元测试。

Don't use the [RequiresAuthentication] attribute from Rob's blog. It's meant for a very old pre-release version of MVC. Use the in-box [Authorize] attribute instead.

Since the [Authorize] attribute is written by the MVC team, you don't need to unit test its logic. However, if you want, you can verify that it's applied to your controllers or actions. Simply get the Type or MethodInfo you're interested in, then call its GetCustomAttributes() method to get instances of AuthorizeAttribute. You can inspect those instances for the values that you expect.

If you want, you can look at the source code of AuthorizeAttribute for information on writing your own filter. Additionally, you can look at the official unit test of this type, so if you do end up writing a filter you can use a similar method to write your own type's unit tests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文