How to access .Net core configuration in .Net core test projects
Published: 2024-02-09 07:45:47

**1. Create Test project and Install below nuget packages**
Below nuget package helps to read configuration in .Net core test project

- `install-package Microsoft.Extensions.Configuration.Json `

- `install-package Microsoft.Extensions.Configuration.EnvironmentVariables`

- `install-package Microsoft.Extensions.Configuration.Binder`

- On top of your AuthorizeDotNetTests class, add a using statement:
`using Microsoft.Extensions.Configuration;`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oswdjgtdz3yxxhntre7n.png)

[.NET Core](https://dotnet.microsoft.com/en-us/) test project configuration is very easy to configure and use. [.Net Core Configuration Management Extensions](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbinder.bind?view=dotnet-plat-ext-8.0&viewFallbackFrom=aspnetcore-2.1) reduces your learning curve and you should be able to write your first test method that will retrieve .Net core configuration in typed objects very quickly and easily.

So, in this article, we are going to share our experience with [.Net Core](https://dotnet.microsoft.com/en-us/) test project read configuration and how we learned and adjusted our development and configuration of [.Net Core](https://dotnet.microsoft.com/en-us/) to make it work for us in the best way. Let's get started with it.

**2 Put below code in appsettings.json in Testproject**
Right click on appsettings.json click on properties and set CopyToOutput Directories to copy if newer.This configuration contains connectionstring,environment etc as per test project requirement.

```
{

 "SystemConfiguration": 
  {
    "ApplicationName": "CPN",
    "ConnectionString": null,
    "ApplicationBasePath": "/",
    "ApplicationHomeUrl": "https://localhost:5000",
    "DevelpmentEnvironmentConfigSettings": {
    "environment": "Development",
    "connectionString": "Host=localhost;Username=test;Password=test123;Database=Test_WebDb",
    "apiLoginID": "Devtest",
    "apiTransactionKey": "key123",
    "displayText": "DispText",
    "displayValue": "Dispalva"
                                            },
  "StagingEnvironmentConfigSettings":       {
   "environment": "Staging",
   "connectionString": "Host=Test\\SQLEXPRESS;Username=test;Password=test123;Database=Test_WebDb",
   "apiLoginID": "StagTest",
   "apiTransactionKey": "StagKye",
   "displayText": "StagDisplayText",
   "displayValue": "StagDisplayValue"
 	                                     },

  "ProductionEnvironmentConfigSettings": {
   "environment": "Production",
   "connectionString": "Host=Test\\SQLEXPRESS;Username=test;Password=test123;Database=Test_WebDb",
   "apiLoginID": "ProdTest",
   "apiTransactionKey": "ProdKye",
   "displayText": "ProdDisplayText",
   "displayValue": "ProdDisplayValue"
	}
    }
}
```

**3.Add below classes in Test project**
Both json and c# class propeties should be same. This classes helps to hold appsettings.json values. This class gives flexibility to aceess json properties as strongly typed properties.

```
 public class SystemConfiguration
  {
   public EnvironmentConfigSettings DevelpmentEnvironmentConfigSettings { get; set; }
   public EnvironmentConfigSettings StagingEnvironmentConfigSettings { get; set; }
   public EnvironmentConfigSettings ProductionEnvironmentConfigSettings { get; set; }		
  }
```

```
 public class EnvironmentConfigSettings
 {
  public string Environment { get; set; }
  public string ConnectionString { get; set; }
  public string ApiLoginID { get; set; } 
  public string ApiTransactionKey { get; set; }
  public string DisplayText { get; set; }
  public string DisplayValue { get; set; }
 } 
```

**4. Create Helper Methods in TestConfigHelper.cs class for reading configuration from appsettings.json**

```
 1.  GetIConfigurationBase method will add AddJsonFile and Environment Variable whole appsettings.json file. 
   
   2.  Environment.GetEnvironmentVariable method help to identify on which environment code is executing. 
	
   3.  GetSection("SystemConfiguration").Bind(systemConfiguration) will retrieve section from appsettings.json 
       SystemConfiguration and Bind method helps to convert json object to c# object.



  public class TestConfigHelper
  {
   public static IConfigurationRoot GetIConfigurationBase()
   {
	 return new ConfigurationBuilder()
	 .AddJsonFile("appsettings.json", optional: true)
	 .AddEnvironmentVariables()
	 .Build();
	}

   public static EnvironmentConfigSettings GetApplicationConfiguration()
  {			
    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    var systemConfiguration = new SystemConfiguration();
    var iTestConfigurationRoot = GetIConfigurationBase();
    iTestConfigurationRoot.GetSection("SystemConfiguration").Bind(systemConfiguration);
      
   if (environment != null)
   {
    if (environment.ToLower() == "Development".ToLower())
    {
    return systemConfiguration.DevelpmentEnvironmentConfigSettings;
    }
	else if (environment.ToLower() == "Staging".ToLower())
    {
	return systemConfiguration.StagingEnvironmentConfigSettings;
    }
    else if (environment.ToLower() == "Production".ToLower())
    {
     return systemConfiguration.ProductionEnvironmentConfigSettings;
    } 
  
 return null;
  }

  }

}
  
```

**5.Read configuration in Test Methods**

```
In constructor of AuthorizeDotNetTests class with the help of TestConfigHelper.GetApplicationConfiguration() method we are loading configurations and in ReadConfiguration  method
  we are retrieving values of configurations using strongly typed properties.Run the mehthod and you will able to acess configuration in test method.


 public class AuthorizeDotNetTests
 {
    public EnvironmentConfigSettings environmentConfigSettings { get;set; }	
   
	public AuthorizeDotNetTests()
    {
     environmentConfigSettings = TestConfigHelper.GetApplicationConfiguration();
  }
  
   [Fact]
   public void ReadConfiguration()
   {
    string connectionstring = environmentConfigSettings.ConnectionString;
    string apiTransactionKey = environmentConfigSettings.ApiTransactionKey;
    string Environment = environmentConfigSettings.Environment;
    string ApiLoginID = environmentConfigSettings.ApiLoginID;
    string ApiTransactionKey = environmentConfigSettings.ApiTransactionKey;			
    string DisplayText = environmentConfigSettings.DisplayText;
    string DisplayValue = environmentConfigSettings.DisplayValue;
   }
  }
```