Read config data in .Net Core Test project: .Net Core quick posts part IV

Life begins after coffee.

In this post, we will see how to read configuration data in .Net Core Test project.

We always need some configurable data which we can change once the application is deployed. Things are bit changed in .Net Core for reading the configuration.

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:

test1

Visual Studio will create a well-structured application for you.

Add 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:

test3

Once this is done, build the project.

Add 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 Nuget Package Manager and click on Install:

test2

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 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:

 

test4

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 it helps.

Advertisements

3 thoughts on “Read config data in .Net Core Test project: .Net Core quick posts part IV

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s