简体   繁体   中英

Unit Testing with DB connection throws error when connecting to DB

Every time I try to run a unit test with some test methods, I get a NullReferenceException at the first line of the following :

    public DB()
    {            
        this.sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        this.con = new SqlConnection(this.sqlConnectionString);
        this.con.StateChange += new StateChangeEventHandler(this.Connection_StateChange);
    }

After further research I realized I should add an app.config file to my test project. I have no clue what to do with it or what it's used for, though.

Tips on how to proceed?

You need to add a new Connection String section in your app.config with the name ConnectionString (Since that is what you're referencing in your C# code):

<configuration>
    <connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=YourDataSource;Initial Catalog=YourDatabase;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

You will also need to change the actual connectionString value in the app.config file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM