Skip to content

Instantly share code, notes, and snippets.

@fjod
Created July 31, 2019 13:03
Show Gist options
  • Save fjod/1298460dadc7f5d6f37b90c35b9f830c to your computer and use it in GitHub Desktop.
Save fjod/1298460dadc7f5d6f37b90c35b9f830c to your computer and use it in GitHub Desktop.
.net core using UserSecrets in tests
It took me too much time to get it working, so I'll describe steps of how to use UserSecrets in testing.
1. Create Unit test project for .net core
2. reference Microsoft.AspNetCore.Mvc.Testing , Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.UserSecrets
3. Add a user secret tag to your assembly:
[assembly: UserSecretsId("your_user_secret_id")]
namespace XUnitTestProject1
{
...
}
alternatively you can copy it from .net core app project file
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<UserSecretsId>("your_user_secret_id")</UserSecretsId>
</PropertyGroup>
and paste to unit test project file
4. Init configuration as
public class UnitTest1
{
public static IConfiguration Configuration { get; set; }
public UnitTest1()
{
var builder = new ConfigurationBuilder().AddUserSecrets<UnitTest1>();
Configuration = builder.Build();
}
[Fact]
public void Test1()
{
var _connectionStringFromUserSecrets =
Configuration["DataBase:ConnectionString"];
Assert.True(_connectionStringFromUserSecrets.Length>0);
}
}
5. Now you can use your UserSecrets as in .net core app.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment