如何在dotnet核心测试项目中使用用户机密

问题描述 投票:6回答:3

我想将集成测试的数据库连接字符串存储为用户密码。我的project.json看起来像这样:

{
  ...

  "dependencies": {
    ...
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0"        
  },

  "tools": {
    "Microsoft.Extensions.SecretManager.Tools": "1.1.0-preview4-final"
  },

  "userSecretsId": "dc5b4f9c-8b0e-4b99-9813-c86ce80c39e6"
}

我已将以下内容添加到我的测试类的构造函数中:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddUserSecrets();

但是,当我运行测试时,当它到达该行时抛出以下异常:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.Configuration.UserSecrets.dll but was not handled in user code

Additional information: Could not find 'UserSecretsIdAttribute' on assembly 'dotnet-test-nunit, Version=3.4.0.0, Culture=neutral, PublicKeyToken=null'.

我错过了什么或是我想要不支持的东西吗?

unit-testing configuration .net-core app-secret
3个回答
4
投票

请参阅https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html中的说明,特别是在InitialiseTest中添加

// the type specified here is just so the secrets library can 
            // find the UserSecretId we added in the csproj file
            var builder = new ConfigurationBuilder()
                .AddUserSecrets<HttpClientTests>();

            Configuration = builder.Build()

但请注意,它不允许在构建服务器上运行测试


2
投票

您必须在应用程序的Startup中指定UserSecretsId。

[assembly: UserSecretsId("xxx")]
namespace myapp
{
    public class Startup
    {
    ...

然后你必须在测试项目中使用.AddUserSecrets(Assembly assembly)的重载。例:

.AddUserSecrets(typeof(Startup).GetTypeInfo().Assembly)

资料来源:https://stackoverflow.com/a/40775511/5270073


-3
投票

对于设置,您可以使用appsettings.json,而不是project.json。它看起来像这样:

{
    "userSecretsId": "dc5b4f9c-8b0e-4b99-9813-c86ce80c39e6"
}

确保通过更改project.json将文件复制到输出:

"buildOptions": {
    "copyToOutput": "appsettings.json"
}

现在您可以像这样检索秘密:

[Fact]
public MyTest()
{
    var appSettings = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    var secret = appSettings["userSecretsId"]
}
© www.soinside.com 2019 - 2024. All rights reserved.