How to use user secrets in a dotnet core test project
Solution 1
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
Solution 2
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
Related videos on Youtube
Paul Hunt
I have been a professional software engineer for over 20 years and I currently specialise in the Microsoft stack, mainly focusing on ASP.NET, C# and SQL Server.
Updated on September 16, 2022Comments
-
Paul Hunt over 1 year
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?
-
Paul Hunt about 7 yearsThis just seems to tell me how to use secrets in an ASP.NET project which is not what I'm doing here. I already have a separate web project in which I'm successfully using secrets, what I'm asking about is a class library test project.
-
kloarubeek about 7 yearsSorry, I overlooked that one, I'll see if there's a solution for that.
-
kloarubeek about 7 yearsthis one should do the trick :-). I think you forgot the copyToOutput.
-
Aage about 2 yearsMake sure you use the
Microsoft.Extensions.Configuration.UserSecrets
nuget package
to be able to use theAddUserSecrets
method.