Using the BaseControllerTest, currently only available in the trunk, we can pass a mocked Context and Controller to a Filter and unit test it:
[TestFixture] public class SecurityFilterTests : BaseControllerTest { [Test] public void SuccessTest() { // Create a controller to pass to the filter AccountController controller = new AccountController(); // Initialise controller PrepareController(controller, "", "account", "index"); // Create the filter we want to test SecurityFilter filter = new SecurityFilter(); // Create a new user ForumOwner owner = new ForumOwner(); owner.Save(); // And simulate a logged-in user by adding them to the session Context.Session["forumOwner"] = owner.Id; // Now that we have logged in, running the filter will return true Assert.IsTrue(filter.Perform(ExecuteEnum.BeforeAction, Context, Context.CurrentController)); } [Test] public void FailTest() { // Create a controller to pass to the filter AccountController controller = new AccountController(); // Initialise controller PrepareController(controller, "", "account", "index"); // Create the filter we want to test SecurityFilter filter = new SecurityFilter(); // No user in the session, therefore the filter will return false to stop execution Assert.IsFalse(filter.Perform(ExecuteEnum.BeforeAction, Context, Context.CurrentController)); // Check if the controller was redirected to the login action as expected Assert.AreEqual("/account/login/", Response.RedirectedTo); } }
