1

I'm trying to get the connection string which is set up in the app.config. Initially, the project didn't have the app config, so I had to add it. In my main project, I have the DLL referencing the configuration but in the unit test project, there is not any configuration dll reference.

Let me mention that I'm trying to test a customer service that I mock with the Moq framework, however when it gets to get the configuration string down the line, it throws an exception.

Any ideas what goes wrong here?

enter image description here

This is the Null Reference exception I get enter image description here

And below is the app.config file

enter image description here

Csibi Norbert
  • 529
  • 4
  • 17

2 Answers2

0

It works for me and is easy to use

Program.cs

var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("app.json");
var configuration = builder.Build();
string constr = configuration["myConnectionString"];

app.json

{       
    "myConnectionString": "server=.\\sqlexpress;database=.......;uid=sa;password=.....;"
}

1) If you are working in debug mode, the app.json file must be in the folder where the program was compiled

2) don't forget to include the necessary libraries

0

In your solution explorer, do the following

  1. Right Click on your app.json
  2. Select "Properties"
  3. In the properties Menu go to the "Advanced" section
  4. Go to "Copy to Output Directory"
  5. Select "Copy Always" or "Copy if newer"
  6. Rebuild your solution and try again

This should work for Debug or Release mode

Properties

Copy If Newer

EDIT: In addition, if you are testing your code from a test project, you will need a separate (or linked) app.json in your test project. That is because your test project will be utilizing it's own settings to test your code

bestfriendkumar
  • 648
  • 1
  • 8
  • 18