Dashboard > MonoRail > Home > Unit Testing Filters
Unit Testing Filters
Added by Colin Ramsay, last edited by Colin Ramsay on May 30, 2007
Labels: 
(None)


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);
        }
    }

Site running on a free Atlassian Confluence Community License granted to Castle Project. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.4 Build:#809 Jun 12, 2007) - Bug/feature request - Contact Administrators