How could I unit test use this .Net code (refactoring allowed)

I was spinning my wheels now, trying to figure out how I can unit test use the following code. At first I was going to use Moq to mock everything, but it does not include the ability to mock private classes. I know that I need to abstract from implementation calls (Configuration) using an interface? but I cannot get everything to work correctly.

The code can be modified, but I would prefer to keep the methods static, unless you can provide good reasons not to. You can add interfaces or create any seams. Alternatively, GetConnStringByName () can be reorganized to return the corresponding string instead of ConnectionStringSettings.

Thoughts?

namespace Stackoverflow.Rocks
{
    /// <summary>
    /// Utility class for progmattically selecting values from the Web.config file.
    /// </summary>
    public class WebConfigStrings
    {
        //private static Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

        /// <summary>
        /// Retrieves the desired connection string value based upon the target name.
        /// </summary>
        /// <param name="connectionStringName">The target connection string referenced in the Web.Config</param>
        /// <returns>The value specified in the Web.Config by your connectionStringName</returns>
        public static ConnectionStringSettings GetConnStringByName(string connectionStringName)
        {
            Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            ConnectionStringSettings connString;
            connString = rootWebConfig.ConnectionStrings.ConnectionStrings[connectionStringName];
            return connString;
        }

        /// <summary>
        /// Retrieves the desired application string value based upon the target name.
        /// </summary>
        /// <param name="applicationStringName">The target application string referenced in the Web.Config</param>
        /// <returns>The value specified in the Web.Config by your applicationStringName</returns>
        public static string GetAppStringByName(string applicationStringName)
        {
            string appString = "";
            appString =  ConfigurationManager.AppSettings[applicationStringName];
            return appString;
        }

    }
}
+3
4

, , , , .

0

, System.Web.Abstractions. , ( ) , asp.net. mocks .

+2

- . , Moq/RhinoMocks. TypeMock , , Telerik JustMock, ( ).

, , . , , , , , .

.

0

- , , System.Web (ShimsContext.Create()) :

System.Web.Configuration.Fakes.ShimWebConfigurationManager.ConnectionStringsGet = () => new ConnectionStringSettingsCollection(){ new ConnectionStringSettings("name", "fake connection string")};

, , , , .

0

Source: https://habr.com/ru/post/1784085/


All Articles