如何使用ASP.NET MVC对网页授权进行单元测试?

时间:2021-06-13 01:44:35

Let's say you have a profile page that can only be accessed by the owner of that profile. This profile page is located at:

假设您有一个只能由该个人资料的所有者访问的个人资料页面。此个人资料页面位于:

User/Profile/{userID}

Now, I imagine in order to prevent access to this page by other users, you could structure your UserController class's Profile function to check the current session's identity:

现在,我想,为了防止其他用户访问此页面,您可以构建UserController类的Profile函数来检查当前会话的标识:

HttpContext.Current.User.Identity.Name

If the id matches the one in the url, then you proceed. Otherwise you redirect to some sort of error page.

如果id与url中的id匹配,则继续。否则,您将重定向到某种错误页面。

My question is how do you unit test something like this? I'm guessing that you need to use some sort of dependency injection instead of the HttpContext in the controller to do the check on, but I am unclear what the best way to do that is. Any advice would be helpful.

我的问题是你如何对这样的东西进行单元测试?我猜你需要使用某种依赖注入而不是控制器中的HttpContext来进行检查,但我不清楚最好的方法是什么。任何意见将是有益的。

4 个解决方案

#1


1  

The link above is a good one. I would also add that instead of programmatically checking the User.Identity.Name value, you should use the Authorize attributes as outlined in the article:

上面的链接很好。我还要添加,而不是以编程方式检查User.Identity.Name值,您应该使用文章中概述的Authorize属性:

http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

#2


1  

I ended up going with the "UserNameFilter" shown in Kazi Manzur's blog post. Works like a charm and easy to unit test.

我最终选择了Kazi Manzur博客文章中的“UserNameFilter”。像魅力和易于单元测试的工作。

#3


1  

You can probably do it by using a fake for the controller context. Check out this article: http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

你可以通过使用假的控制器上下文来做到这一点。看看这篇文章:http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

#4


0  

This is where mocking comes in, with a fake HttpContext.

这是模拟进来的地方,带有假的HttpContext。

#1


1  

The link above is a good one. I would also add that instead of programmatically checking the User.Identity.Name value, you should use the Authorize attributes as outlined in the article:

上面的链接很好。我还要添加,而不是以编程方式检查User.Identity.Name值,您应该使用文章中概述的Authorize属性:

http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

#2


1  

I ended up going with the "UserNameFilter" shown in Kazi Manzur's blog post. Works like a charm and easy to unit test.

我最终选择了Kazi Manzur博客文章中的“UserNameFilter”。像魅力和易于单元测试的工作。

#3


1  

You can probably do it by using a fake for the controller context. Check out this article: http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

你可以通过使用假的控制器上下文来做到这一点。看看这篇文章:http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

#4


0  

This is where mocking comes in, with a fake HttpContext.

这是模拟进来的地方,带有假的HttpContext。