Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone 's Guide to

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

In this post, we will look at how to read configuration data in .NET Core test projects with a few quick and easy steps.

· Web Dev Zone ·
Free Resource

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:

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:

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:

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:

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.

Topics:
web dev ,tutorial ,configuration data ,c# ,.net core

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}