CustomWebApplicationFactory не работает должным образом при миграции ASP. Net с 2.2 на 3.0 - PullRequest
0 голосов
/ 02 августа 2020

Когда я переношу проект с ASP. NET Core 2.2 на 3.0, мои проверки подлинности UnitTests не выполняются. Понятия не имею, нужно ли мне изменять 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();
            } 

My 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>();
        }
    }

HelpFunctions:

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;
        }
    }

TestResult:

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

Интересно, а если что-то не так с настройкой customWebApplicationFactory?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...