首页 > 解决方案 > 将 ASP.Net 从 2.2 迁移到 3.0 时,CustomWebApplicationFactory 无法正常工作

问题描述

当我将项目从 ASP.NET Core 2.2 迁移到 3.0 时,我的身份验证单元测试失败。我不知道在迁移时是否需要修改 CustomWebApplicationFactory,我在 ASP.NET 教程上没有找到它的信息。请帮我弄清楚。谢谢。

这是我的代码:

UserControllerAuthTests:
    [TestMethod]
            public async Task UserController_No_Auth_Should_Fail()
            {
                // Arrange
                var client = new CustomWebApplicationFactory().CreateClientWithoutTestAuth();
    
                // Act
                var response = await client.GetAsync("User/Index");
                // Assert
                Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode);
                // change it to Contains "Identity/Account/Login" instead of StartsWith
                Assert.IsTrue(response.Headers.Location.OriginalString.Contains("http://localhost/Identity/Account/Login"));
    
                client.Dispose();
            } 

我的 CustomWebApplicationFactory:

CustomWebApplicationFactory:
public class CustomWebApplicationFactory : WebApplicationFactory<MockStartup>
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
        }

        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return WebHost.CreateDefaultBuilder()
                .UseStartup<MockStartup>();
        }
    }

帮助功能:

public static class WebApplicationFactoryExtensions
    {
        // Method which adds TestAuthHandler to AuthenticationBuilder
        public static AuthenticationBuilder AddTestAuth(this AuthenticationBuilder builder, Action<AuthenticationSchemeOptions> configureOptions)
        {
            return builder.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", "Test Auth", configureOptions);
        }

        // Method which added Authentication to factory using ConfigureTestServices.
        // We provide TestClaimsProvider as parameter which is adde to services.
        public static WebApplicationFactory<T> WithAuthentication<T>(this WebApplicationFactory<T> factory, TestClaimsProvider claimsProvider) where T : class
        {
            return factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    // Schema name must match with Schema added to AuthenticationBuilder
                    services.AddAuthentication(options => {
                        options.DefaultAuthenticateScheme = "Test";
                        options.DefaultChallengeScheme = "Test";
                    }).AddTestAuth(o => { });
                    services.AddScoped<TestClaimsProvider>(_ => claimsProvider);
                });
            });
        }

        // Method used to create a mock client with authentication based on providing Claims.
        public static HttpClient CreateClientWithTestAuth<T>(this WebApplicationFactory<T> factory, TestClaimsProvider claimsProvider) where T : class
        {
            var client = factory.WithAuthentication(claimsProvider).CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test");

            return client;
        }

        // Method used to create mock client without any authentication.
        public static HttpClient CreateClientWithoutTestAuth<T>(this WebApplicationFactory<T> factory) where T : class
        {
            var client = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });

            return client;
        }
    }

测试结果:

Assert.AreEqual failed. Expected:<Redirect>. Actual:<NotFound>. 

我想知道 customWebApplicationFactory 设置是否有问题?

标签: asp.netmigration

解决方案


推荐阅读