c# - Web API 与 Azure Key Vault 的集成测试

标签 c# azure asp.net-core integration-testing azure-keyvault

我按照教程here进行操作但启动文件似乎无法识别 appsetting.json 文件。

因此,当我运行实际项目时,Iconfiguration 有 7 个属性。 enter image description here

但是当我运行测试时,它只有一个属性。 enter image description here

所以我想也许我在配置 AppSetting.json 文件的测试方法中遗漏了一些内容..

这是我的测试方法:

  public class StudentServiceRequestsTest
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;

        public IndividualServiceRequestsTest()
        {
            // Arrange
            _server = new TestServer(new WebHostBuilder()
                .UseStartup<Startup>());
            _client = _server.CreateClient();
        }
        [Fact]
        public async Task GetStudentsByDeptShould()
        {
            try
            {
                //Act
                var response = await _client.GetAsync("/api/department/200/students");
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync();

                //Assert
                Assert.Equal("hi", responseString);
            }
            catch (Exception e)
            {
                throw;
            }

        }

这是我的启动类,显然我添加了 json 文件,其中包含 Web API 中所需的所有 key 和 secret 。

namespace CIS.API.Student
{
    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        public IConfiguration Configuration { get; set; }
            services.AddSingleton(Configuration);
            services.AddMvc();
        }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(x => x
                 .AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()
                 .AllowCredentials());

            app.UseMvc();

        }
    }
}

有谁知道为什么会发生这种情况吗?

最佳答案

经过一些研究,包括教程:Integration tests in ASP.NET Core ,我让它工作了。

第1步:将“appsetting.json”文件复制到集成测试项目。

第 2 步:将测试类构造函数修改为:

 public class StudentServiceTest 
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;
        public StudentServiceTest()
        {
            var config = new ConfigurationBuilder().SetBasePath(Path.GetFullPath(@"..\..\..\..\Student.IntegrationTest"))
                                                   .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                                   .AddEnvironmentVariables();
            var builtConfig = config.Build();
            config.AddAzureKeyVault(
                    $"https://{builtConfig["Vault"]}.vault.azure.net/",
                    builtConfig["ClientId"],
                    builtConfig["ClientSecret"]);
            var Configuration = config.Build();

            _server = new TestServer(WebHost.CreateDefaultBuilder()
                .UseConfiguration(Configuration)
                .UseStartup<Startup>());
            _client = _server.CreateClient();
            _client.BaseAddress = new Uri("http://localhost:xxxxx");
        }

        [Fact]
        public async Task StudentShould()
        {
            try
            {
                //Act
                var response = await _client.GetAsync("/api/getStudentByID/200");
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync();

                //Assert
                Assert.Equal("bla bla", responseString);
            }
            catch (Exception e)
            {
                throw;
            }

        }
}

关于c# - Web API 与 Azure Key Vault 的集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991110/

相关文章:

c# - 在 ASP.NET 和 XDocument.Load 中获取文件路径

Azure YAML-Pipeline 跳过作业,我不知道为什么

c# - 在现有应用程序中添加 Azure AD 身份验证

c# - 如何使用 CSVHelper 编写非平面类的 header ?

c# - Identity Owin 是否需要延迟加载?

c# - ASP.Net Core MVC Ajax json 响应

c# - 如何使用 View Component 按名称调用 PartialView 而不是加载 default.cshtml

visual-studio - 调试 ASP.Net 应用程序时 Visual Studio 未启动浏览器

c# - 在windows/.net中创建管道文件

python - upload_blob函数中的Azure python asyncio内存耗尽