62

Read Config Data in .NET Core Test Project: .NET Core Quick Posts, Part IV

 5 years ago
source link: https://www.tuicool.com/articles/hit/NryY7rQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this post, we will see how to read configuration data in .NET Core test projects.

We'll need some configurable data which we can change once the application is deployed. Things have changed a bit in .NET Core when it comes to reading configuration data.

Let us see how to do it.

Prerequisite:

  • Visual Studio 2017 community edition, download here .
  • .Net Core 2.0 SDK from here (I have written a post to install SDK here ).

Create the Test Project Using .NET Core 2.0 Template in VS 2017

Once you have all these installed, open your Visual Studio 2017 -> Create New Project -> Select xUnit Test Project:

zqmEvuZ.png!web Visual Studio will create a well-structured application for you.

Add a Config JSON File

Let us add the config file from which we will read the configuration key-value pair.

I named the file as my-config.json. Add below values for now:

{
  "my_Key_1": "value1",
  "my_key_2": "value2"
}

Right-click on the my-config.json file -> click on Properties -> select Copy if newer:

ZbmuIfF.png!web

Once this is done, build the project.

Add a NuGet Package

Next step is to add the NuGet pckage which we will require to read the data from the JSON file which we just added.

Search with "Microsoft.Extensions.Configuration.Json" in the NuGet Package Manager and click on Install:

MRn2iyn.png!web

This Nuget package is a JSON configuration provider implementation for Microsoft.Extensions.Configuration.

Use it in the Test Method

Now let us use this NuGet package to read the configuration data.

Add the below code in the test method:

var config = new ConfigurationBuilder()
 .AddJsonFile("my-config.json")
 .Build();

var clientId = config["my_Key_1"];

Here, ConfigurationBuilder   is part of Microsoft.Extensions.Configuration.

That is it. Now we can read the config data as you can see below:

Fneiqey.png!web

value1   is returned which is the value of the key,  my_key_1 .

Hence you can read the config data for the .NET Core test project.

Hope this helps.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK