Created
July 31, 2019 13:03
-
-
Save fjod/1298460dadc7f5d6f37b90c35b9f830c to your computer and use it in GitHub Desktop.
.net core using UserSecrets in tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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