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:
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:
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:
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:
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.
I’m trying to read the appsettings.json file of the project being tested from the test project. I couldn’t find a better way than creating a symlink, which I guess is not the best option. Do you have any idea how could I achieve it in a more suitable way? Have a look at this question at SO: https://stackoverflow.com/questions/50539522/read-configuration-from-project-being-tested-when-running-integrations-test-in-d
LikeLike
Hey, sorry for late reply. I guess you have found the answer already right?
LikeLike