Search code examples
c#winformsconnection-stringapp-configclass-library

Reading a connection string from a class library


I am currently struggling to read a connection string from the App.config inside my WinForms application from my Class Library (and Unit Testing).

I added a 'test' entry to the App.config;

<connectionStrings>
     <add name="MyConnString" connectionString="Test;" />
</connectionStrings>

My TestMethod looks like this;

    [TestMethod]
    public void TestConnection1()
    {
        string connString = "";

        if (ConfigurationManager.ConnectionStrings["MyConnString"] != null)
        {
            connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
        }

        string expected = "Test;";
        string actual = connString;

        Assert.AreEqual(expected, actual);
    }

This, obviously, fails. Actual's value is empty. What am I doing wrong?

enter image description here


Solution

  • you need to add connection string key into Test project's config as well.