简体   繁体   English

.NET Core 2.0 用户机密和单元测试

[英].NET Core 2.0 User Secrets and Unit Testing

I'm currently working on a .net core solution (multiple projects) that uses Microsoft's app secrets management .我目前正在研究使用Microsoft 的应用机密管理的 .net 核心解决方案(多个项目)。 I can pull secrets back in my runtime project (eg Console app), but when it comes to leveraging user secrets for integration tests in a separate project (eg Model.Test project), what's the right approach?我可以在我的运行时项目(例如控制台应用程序)中提取秘密,但是当涉及在单独的项目(例如 Model.Test 项目)中利用用户秘密进行集成测试时,正确的方法是什么?

I can think of a few options:我能想到几个选择:

  1. Give each project the same UserSecretsId : This seems like it'd made sense for test projects that may leverage the same secrets that the runtime project uses.为每个项目提供相同的UserSecretsId :这对于可能利用运行时项目使用的相同机密的测试项目似乎很有意义。

  2. Let each project have unique UserSecretsId : This would require that the secrets be manually kept in sync on the development machine让每个项目都有唯一的UserSecretsId :这需要在开发机器上手动保持秘密同步

It seems like even between .net core 1.0 and 2.0 user secrets has changed somewhat and I don't have a lot of familiarity with this system in general.似乎即使在 .net 核心 1.0 和 2.0 用户机密之间也发生了一些变化,而且我对这个系统一般不太熟悉。 Thanks!谢谢!

I'm still learning about configuration in .NET Core 2 myself. 我本人仍在学习有关.NET Core 2中的配置的信息。 When I set up my API project I shared the user secrets tag between the project and the unit test project by copying it between them. 设置API项目时,我通过在项目和单元测试项目之间复制用户密钥来共享它们。 Meaning they both had the same user secrets guid, like your option 1. My rationale is that it would be the easiest way to maintain secrets between the two projects for the development team. 意味着它们都具有相同的用户机密guid,就像您的选项1一样。我的理由是,对于开发团队来说,这是在两个项目之间维护机密的最简单方法。

This article from Patrick Huber shows how to reference User Secrets in the config builder which was key for me - https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html Patrick Huber的这篇文章展示了如何在配置构建器中引用用户机密,这对我来说很关键-https: //patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests .html

This article from Rick Strahl was also useful it shows how to configure a test helper in your unit tests for accessing the user secrets: https://weblog.west-wind.com/posts/2018/Feb/18/Accessing-Configuration-in-NET-Core-Test-Projects Rick Strahl的这篇文章也很有用,它说明了如何在单元测试中配置测试助手来访问用户机密: https : //weblog.west-wind.com/posts/2018/Feb/18/Accessing-Configuration- NET核心测试项目

Related implementation question - How to use user secrets in a dotnet core test project 相关实施问题- 如何在dotnet核心测试项目中使用用户机密

Question related to referencing the config file - AppSettings.json for Integration Test in ASP.NET Core 与引用配置文件-AppSettings.json有关的问题, 用于ASP.NET Core中的集成测试

This provides a concrete example using the references that Dale C provided to this question earlier.这提供了一个具体的例子,使用Dale C 之前提供给这个问题的参考资料。

It has been tested with .NET6.它已经过 .NET6 测试。 The example will load configuration from该示例将从

  • appsettings.json appsettings.json
  • secrets.json秘密.json
  • Environment variables环境变量

Create a test project创建一个测试项目

In your test project在您的测试项目中

  1. Add nuget package Microsoft.Extensions.Configuration.UserSecrets添加 nuget package Microsoft.Extensions.Configuration.UserSecrets
  2. In the .csproj file of our test project, add the guid of the user secret we want to access.在我们测试项目的.csproj文件中,添加我们要访问的用户密码的 guid。
<PropertyGroup>
    <UserSecretsId>0e8ea027-2feb-4098-ba69-4a6711e8eee2</UserSecretsId>
</PropertyGroup>
  1. Create a test class创建测试 class
using NUnit.Framework;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;


namespace Example
{
    public class ConfigurationExampleTest
    {
        public IMediator? _mediator { get; set; }
        public IConfiguration config { get; set; }

        [SetUp]
        public void Setup()
        {            
            // The startupPath is simply one way of getting the path to
            // appettings.json. We could hard code tha path if necessary
            // or use any other method to obtain the path to appsettings.json
            var filepath = typeof(WebApp.Startup)
                .Assembly.Location;
            var StartupPath = Path.GetDirectoryName(filepath);

            config = new ConfigurationBuilder()
                .SetBasePath(StartupPath)
                .AddJsonFile("appsettings.json", optional: true)
                .AddUserSecrets<ConfigurationExampleTest>()
                .AddEnvironmentVariables()
                .Build();

           
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder =>
                {
                    builder.UseStartup<WebApp.Startup>();
                })
                .ConfigureServices(services =>
                {
                    // Adds the config to the dependency injection
                    // This makes the config object accessible in
                    // your WebApp/project-under-test
                    services.AddSingleton(config);
                })
                .Build();
             
             // This will get any service we added to the dependency injection
             // in WebApp.Startup
            _mediator = host.Services.GetService<IMediator>();
        }

        [TearDown]
        public void Teardown()
        { }

        [Test]
        public void ExampleTest()
        {            
            // The configuration object will now be available
            // vai dependency ibjection

            // We can use the_mediator instance we got from the
            // dependency injection here
            
            // _mediator.Send(<your request>);
            
        }
    }
}

References:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM