Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject configuration settings in test classes (ASP.NET Core)?

SmtpConfig contains my credentials which I want to use in a test class. appsettings.development.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "SmtpConfig": {
    "credentials": "username:password"
  }
}

Here I configure the smtpConfig to be injected in classes (in controller classes works very fine!) Startup.cs

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc();

      services.Configure<SmtpConfig(
         Configuration.GetSection(nameof(SmtpConfig)
      ));
}

I want to access credentials from appsettings.development.json in tests, because on another server I will have another config file.

//important usings
using Microsoft.Extensions.Options;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
    public class SomeControllerAPITest
    {
       private SmtpConfig _smtpConfig;

        public SomeControllerAPITest(IOptions<SmtpConfig> smtpConfig)
        {
            _smtpConfig = smtpConfig.Value;
        }


        [TestMethod]
        public void Post_ReturnsCreatedInstance()
        {
            var credentials = _smtpConfig.credentials;

            //use that credentials
            ...

            //call remote server
            ...
        }
}

Is it possible to do that?

like image 223
Alex Avatar asked Jul 05 '17 07:07

Alex


People also ask

How do you inject IConfiguration in NET Core 6?

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // TODO: Service configuration code here... } public void Configure(IApplicationBuilder app, ...


1 Answers

- Create class file into testProject

public static IConfiguration getConfig(){ 
   var config = new ConfigurationBuilder() 
     .SetBasePath("/Users/Project/")
     .AddJsonFile("appsettings.json")  
     .Build(); 
   return config; 
}

    [TestClass]
    public class TestMasterClass
    {
        public static IConfiguration _configuration { get; set; }

        public TestMasterClass()
        {
            _configuration = AnotherClassFile.getConfig();
        }

        [TestMethod]
        public void TestConfigElasticSearch()
        {

            var elasticSearch = _configuration["ElasticSearchConfig:Link01"];
            Assert.IsNotNull(elasticSearch);
        }
    }
like image 135
Jonathan Troncoso Avatar answered Oct 22 '22 23:10

Jonathan Troncoso