How to use user secrets in a dotnet core test project

点点圈 提交于 2019-12-05 02:32:42

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

Ricardo Fontana

You must specify the UserSecretsId in Startup of your application.

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

Then you have to use the overload of .AddUserSecrets(Assembly assembly) in your test project. Example:

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

Source: https://stackoverflow.com/a/40775511/5270073

For settings you can use appsettings.json, not the project.json. It looks like this:

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

Make sure to copy the file to output by changing the project.json:

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

Now you can retrieve the secret like this:

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

    var secret = appSettings["userSecretsId"]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!