mercredi 5 juillet 2017

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?

Aucun commentaire:

Enregistrer un commentaire