views:

63

answers:

3

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?

+1  A: 

The unit test project uses its own config file. Does the connection string exist in that file as well?

Chris Lively
A: 

config.ConnectionStrings usually will try to read the app/web.config file of the process executing this code. So you might need to add an app.config file containing the connection string inside your unit test project.

Darin Dimitrov
A: 

Personally I would suggest seperating out your encryption test method into a more generic IsStringEncrypted.

That way you can test the encryption method without having to worry about databases, connections strings, or web/app.configs.

In your code, you would simply call

String connectionString = GetConnectionStringFromAppConfig(); SKM.IsStringEncrypted(connectionString);

In your unit test, you simply define what connectionString would be for that particular test.

Ben Cawley