Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The problem with NUnit and app.config

When i run a simple test on connection to DB check i receive an error in NUnit:

[Test] public void TestConn() {     string  connectionString = ConfigurationManager.ConnectionStrings["FertigungRead"].ConnectionString;     SqlConnection connection = new SqlConnection(connectionString);     connection.Open();     Assert.AreEqual(ConnectionState.Open, connection.State);     connection.Close();  } 

System.NullReferenceException : Object reference not set to an instance of an object.

on line :

connectionString = ConfigurationManager.ConnectionStrings["FertigungRead"].ConnectionString; 

Can i use ConfigurationManager in tests?

like image 887
Mike Avatar asked Mar 09 '10 13:03

Mike


People also ask

What is the use of app config in C#?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

Why do we need NUnit?

NUnit Testing Framework Each module is tested independently to ensure that the objective is met. The NUnit Framework caters to a range of attributes that are used during unit tests. They are used to define Test -Fixtures, Test methods, ExpectedException, and Ignore methods.


2 Answers

Yes, you can. You need to be sure that any configuration you are referencing in your tests actually exist in the app.config of the test project.

In other words, the project where your test is in, does not have a connection string "FertigungRead" defined in its app.config.

One way to do this is to add the app.config of the system under test to the test project as a link, this way any changes happen on both projects.

like image 107
Oded Avatar answered Sep 19 '22 09:09

Oded


  1. Go to NUnit/Project/Edit...
  2. In Configuration Property panel go to Configuration File Name
  3. Put there yourAssemblyName.dll.config

NB: if does not work try to add path to it, e.g. bin\Debug\ yourAssemblyName.dll.config

Your test project file yourAssemblyName.nunit will be updated.

And yes, be sure App.config in your test project match to what you access in test, i.e.

[Test] public void TestConn() {    var sss = ConfigurationManager.AppSettings["TestKey"]; } 

App.config

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <appSettings>     <add key="TestKey" value="testKeyValue"/>   </appSettings> </configuration> 
like image 44
ivan_d Avatar answered Sep 18 '22 09:09

ivan_d