首页 > 解决方案 > 使用 cookie 身份验证为 REST 服务设置 MSTest 的最佳方法?

问题描述

背景:我正在使用 ASP.NET Core 3.1,并集成测试需要 cookie 身份验证的 REST 服务。

下面的候选解决方案。

笔记:

using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WebApi; // Contains my Startup.cs

namespace WebApiTest
{
    [TestClass]
    public class UserTest
    {
        static IHost HttpHost;

        [ClassInitialize]
        public static async Task ClassStartup(TestContext context)
        {
            HttpHost = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .Build();
            await HttpHost.StartAsync();
        }

        [ClassCleanup]
        public static async Task ClassCleanup()
        {
            await HttpHost.StopAsync();
        }

        public static HttpContent GetHttpContent(object content)
        {
            HttpContent httpContent = null;

            if (content != null)
            {
                httpContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(content, content.GetType()));
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            }

            return httpContent;
        }

        public static HttpClient GetCookieHttpClient()
        {
            SocketsHttpHandler handler = new SocketsHttpHandler
            {
                AllowAutoRedirect = false,
                CookieContainer = new CookieContainer(),
                UseCookies = true
            };

            return new HttpClient(handler);
        }

        [TestMethod]
        public async Task GetUserData_ReturnsSuccess()
        {
            using (HttpClient client = GetCookieHttpClient())
            {
                var credentials = new
                {
                    Email = "test@test.com",
                    Password = "password123",
                };

                HttpResponseMessage response = await client.PostAsync("http://localhost:5000/api/auth/login", GetHttpContent(credentials));
                response = await client.GetAsync(String.Format("http://localhost:5000/api/users/{0}", credentials.Email));
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            }
        }
    }
}

标签: c#asp.net-coreintegration-testingmstest

解决方案


HttpClient是一个瘦客户端;除非您明确告诉它,否则它不会做任何事情。换句话说,它永远不会为您发送 cookie;您必须为请求添加一个标头,其中包含每个请求Cookie的 cookie 值。测试服务器“客户端”只是设置为向测试服务器代理请求的实例。您应该按照规定使用测试服务器及其客户端,然后添加您使用它发出的请求的标头。HttpClientCookie


推荐阅读