如何在 UnitTest 中模拟 AntiForgeryToken

how to mock antiforgerytoken in unittest

提问人:Ali Eshghi 提问时间:3/27/2023 更新时间:3/27/2023 访问量:96

问:

我正在尝试为具有 ValidateAntiForgeryToken 属性的 post 方法编写集成测试。所以这是我的代码:controller

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ChangeAgent([FromBody]ChangeAgentRequestViewModel model)
         
        {
            try
            {
                var test = Request.Headers;
                model.ProfileId = CandidateInfo.ProfileId;
                model.InsUser = CandidateInfo.Id;
                var res = await _agentService.SaveAgent(model);
                return Json(res);
            }
            catch (AntiforgeryValidationException ex)
            {

                throw;
            }

           
        }

所以我创建了集成测试,并尝试获得这样的防伪令牌:WebApplicationFactory

[TestFixture]
    public class BaseIntegrationUnitTest
    {
        protected readonly HttpClient _httpClient;
        protected string _token;
        protected string _cookitoken;
        protected readonly IAntiforgery _antiforgery;
        protected BaseIntegrationUnitTest()
        {
            var appFactory = new WebApplicationFactory<Program>();
            _antiforgery = appFactory.Services.GetService<IAntiforgery>();
            var tokenSet = _antiforgery.GetAndStoreTokens(new DefaultHttpContext());
            _token = tokenSet.RequestToken;
            _cookitoken = tokenSet.CookieToken;

            _httpClient = appFactory.CreateClient();
            

            //_token = httpContextAccessor.HttpContext.Request.Cookies["XSRF-TOKEN"];
        }
   }

在我的测试中,我做了这样的事情:

public class AgentIntegrationTest : BaseIntegrationUnitTest
    {
[Test]
        public async Task ChangeAgent_OnModelStateUnvalid_ReturnFalse()
        {            
             await Login();
            var antiforgeryOptions = new AntiforgeryOptions
            {
                SuppressXFrameOptionsHeader = true
            };
            
            var uri = new Uri("http://localhost:5075/Agent/ChangeAgent");

            var myModel = new ChangeAgentRequestViewModel
            {...}
            var json = JsonConvert.SerializeObject(myModel);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(antiforgeryOptions.HeaderName, _token);
            _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", $"{antiforgeryOptions.Cookie.Name}={_cookitoken}" );
            var response = await _httpClient.PostAsync(uri, content);


            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsStringAsync();
       }
   }

我得到的响应是它没有登陆我的控制器,(如果我评论它工作正常)。我怎样才能嘲笑这个代币?我正在使用 dotnet core 6。400 bad requestValidateAntiForgeryToken

ASP.NET-MVC 单元测试 .NET-Core AntiforgeryToken

评论


答: 暂无答案