C# why unit test has this strange behaviour?

Posted by 5YrsLaterDBA on Stack Overflow See other posts from Stack Overflow or by 5YrsLaterDBA
Published on 2010-06-10T15:09:21Z Indexed on 2010/06/10 15:12 UTC
Read the original article Hit count: 185

Filed under:
|

I have a class to encrypt the connectionString.

    public class SKM
        {
            private string connStrName = "AndeDBEntities";

        internal void encryptConnStr()
        {
            if(isConnStrEncrypted())
                return;
            ...
        }

        private bool isConnStrEncrypted()
        {
            bool status = false;
            // Open app.config of executable.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // Get the connection string from the app.config file.
            string connStr = config.ConnectionStrings.ConnectionStrings[connStrName].ConnectionString;

            status = !(connStr.Contains("provider"));
            Log.logItem(LogType.DebugDevelopment, "isConnStrEncrypted", "SKM::isConnStrEncrypted()", "isConnStrEncrypted=" + status);
            return status;

        } 

   }

Above code works fine in my application. But not in my unit test project.

In my unit test project, I test the encryptConnStr() method. it will call isConnStrEncrypted() method. Then exception (null pointer) will be thrown at this line:

string connStr = config.ConnectionStrings.ConnectionStrings[connStrName].ConnectionString;

I have to use index like this to pass the unit test:

string connStr = config.ConnectionStrings.ConnectionStrings[0].ConnectionString;

I remember it worked several days ago at the time I added above unit test. But now it give me an error. The unit test is not integrated with our daily auto build yet. We only have ONE connectionStr. It works with product but not in unit test. Don't know why. Anybody can explain to me?

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing