如何在测试类中注入配置设置(ASP.NET Core)?

时间:2017-07-05 07:00:58

标签: c# unit-testing testing dependency-injection smtp

SmtpConfig包含我想在测试类中使用的凭据。 appsettings.development.json

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

这里我配置要在类中注入的smtpConfig(在控制器类中工作得非常好!) Startup.cs

public IConfigurationRoot Configuration { get; }

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

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

我想在测试中从appsettings.development.json访问凭据,因为在另一台服务器上我将有另一个配置文件。

//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
            ...
        }
}

有可能吗?

2 个答案:

答案 0 :(得分:0)

您可以使用相同的Microsoft.Extensions.Configuration绑定功能来构建相同填充的IOptions<TConfiguration>实例。这是我们如何为测试代码实现这一点的粗略等价物:

public class TestSmtpConfigOptions : IOptions<SmtpConfig> {

    private static Lazy<SmtpConfig> configuration { get; }

    static TestSmtpConfigOptions() {
        configuration = new Lazy<SmtpConfig>(GetConfiguration);
    }

    public SmtpConfig Value {
        get { return configuration.Value; }
    }

    private static SmtpConfig GetConfiguration() {
        var configuration = new SmtpConfig();
        var path = Path.Combine("config", "appsettings.development.json");

        new ConfigurationBuilder()
            .SetBasePath("path/to/base/directory/of/project")
            .AddJsonFile(path, optional: true)
            .Build()
            .GetSection(nameof(SmtpConfig))
            .Bind(configuration);

        return configuration;
    }

}

然后,在你的灯具中,你只需要实例化它:

[TestClass]
public class SomeControllerAPITest {

    private SmtpConfig _smtpConfig;

    public SomeControllerAPITest() {
        _smtpConfig = new TestSmtpConfigOptions().Value;
    }


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

        //use that credentials
        ...

        //call remote server
        ...
    }
}

如果您关心跨平台路径并且不介意一点额外的复杂性,我们使用这个小课程来为我们的xUnit测试运行器以跨平台方式获取基本路径。这意味着我们在上面的示例中使用TestConfiguration.BasePath而不是"path/to/base/directory/of/project"

internal static class TestConfiguration {

    internal static string BasePath { get; }

    static TestConfiguration() {
        BasePath = Environment.GetEnvironmentVariable("BASE_DIRECTORY");

        if (BasePath == null) {
            BasePath = AppContext.BaseDirectory;

            // cross-platform equivalent of "../../../../../"
            for (var index = 0; index < 5; index++) {
                BasePath = Directory.GetParent(BasePath).FullName;
            }
        }
    }

    internal static string ResolvePath(string relativePath) {
        return Path.Combine(BasePath, relativePath);
    }

}

答案 1 :(得分:0)

-将类文件创建到testProject

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

[TestClass]     公共课程TestMasterClass     {         公共静态IConfiguration _configuration {get;组; }

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


    [TestMethod]
    public void TestConfigElasticSearch()
    {

        var elasticSearch = _configuration["ElasticSearchConfig:Link01"];
        Assert.IsNotNull(elasticSearch);


    }