I have a controller action that automatically redirects to a new page if the user is already logged in (User.Identity.IsAuthenticated
). What is the best way to write a unit test for this scenario to ensure that the redirect takes places?
相关问题
- MVC-Routing,Why i can not ignore defaults,The matc
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
I've been using the following Mocks with Moq to allow setting up various conditions in my unit tests. First, the HttpContextBase mock:
Every property that might provide a useful Mock is set up in here. That way, if I need to add something like a referrer, I can just use:
The "GetPrincipleMock" method is what sets up the user. It looks like this:
Now, my controller setups in the tests look like this:
It's a little bit of verbose setup, but once you have everything in place, testing a variety of conditions becomes a lot easier.
That's not the simplest thing to do, but it can be done. The User property simply delegates to Controller.HttpContext.User. Both are non-virtual read-only properties, so you can't do anything about them. However, Controller.HttpContext delegates to ControllerBase.ControllerContext which is a writable property.
Therefore, you can assign a Test Double HttpContextBase to Controller.ControllerContext before exercising your System Under Test (SUT). Using Moq, it would look something like this:
Then invoke your action and verify that the return result is a RedirectResult.
This test utilizes the implicit knowledge that when you create a GenericIdentity with an empty name, it will return false for IsAuthenticated. You could consider making the test more explicit by using a
Mock<IIdentity>
instead.