如何在 dotnet 核心测试项目中使用用户机密 [英] How to use user secrets in a dotnet core test project
问题描述
我想将集成测试的数据库连接字符串存储为用户机密.我的 project.json 看起来像这样:
I want to store a database connection string for my integration tests as a user secret. My project.json looks like this:
{
...
"dependencies": {
...
"Microsoft.Extensions.Configuration.UserSecrets": "1.1.0"
},
"tools": {
"Microsoft.Extensions.SecretManager.Tools": "1.1.0-preview4-final"
},
"userSecretsId": "dc5b4f9c-8b0e-4b99-9813-c86ce80c39e6"
}
我已将以下内容添加到我的测试类的构造函数中:
I've added the following to the constructor of my test class:
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddUserSecrets();
但是,当我运行测试时,遇到该行时会抛出以下异常:
However when I run the tests the following exception is thrown when it hits that line:
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'.
我是否遗漏了某些东西,或者我想要的东西不受支持?
Have I missed something or is what I'm trying to do not supported?
推荐答案
请参阅 https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html,在特别是在 InitialiseTest 添加
See instructions in https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html, in particular in InitialiseTest add
// 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()
但是请注意,它不允许在构建服务器上运行测试
However note that it will not allow to run tests on build server
这篇关于如何在 dotnet 核心测试项目中使用用户机密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!