Home All Groups Group Topic Archive Search About

Unit Testing a Membership Provider Implementation...

Author
18 Jul 2006 3:54 PM
Geoff
I recently developed a membership provider and wondered how to unit test it
with NUnit. I came up with this simple solution. I do not try to update
config files at runtime and thus I have only used this for reading settings
(no writing).

        public static MyMembershipProvider GenerateProvider( )
        {
            MyMembershipProvider mp = new MyMembershipProvider( );

            //Try the web.config file first...
            string path = HostingEnvironment.ApplicationVirtualPath;

            System.Configuration.Configuration config =
WebConfigurationManager.OpenWebConfiguration (path);

            MembershipSection configSection = ( MembershipSection
)config.GetSection( "system.web/membership" );
            ProviderSettings settings = ( ProviderSettings
)configSection.Providers[mp.Name];

            if ( settings == null )
            {
                //try the web.config file at the root of the default web site
                config = WebConfigurationManager.OpenWebConfiguration( "/" );

                configSection = ( MembershipSection )config.GetSection(
"system.web/membership" );
                settings = ( ProviderSettings
)configSection.Providers[mp.Name];

                if ( settings == null )
                {
                    //try the app.config
                    config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None );
                    configSection = ( MembershipSection )config.GetSection(
"system.web/membership" );
                    settings = ( ProviderSettings
)configSection.Providers[mp.Name];
                }
            }

            if ( settings != null )
            {
                NameValueCollection collection = settings.Parameters;
                mp.Initialize( mp.Name, collection );
            }
            return mp;
        }

I hope this helps someone unit test there custom membership providers.

AddThis Social Bookmark Button