我有一個帶有基本Register頁面的 ASP.NET MVC 應用程式。這是注冊新用戶的具體功能。
注冊.cshtml.cs:
public async Task<IActionResult> OnPostAsync()
{
var returnUrl = Url.Content("~/Home/PostRegister");
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
這是我在集成測驗中為它撰寫的測驗:
[Fact]
public async Task DoesRegisterSucceed()
{
// Arrange
var client = _factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var postRequest = new HttpRequestMessage(HttpMethod.Post, "/Identity/Account/Register");
var formModel = new Dictionary<string, string>
{
{ "Email", "[email protected]" },
{ "Password", "pas3w0!rRd" },
{ "ConfirmPassword", "pas3w0!rRd" },
};
postRequest.Content = new FormUrlEncodedContent(formModel);
var response = await client.SendAsync(postRequest);
response.EnsureSuccessStatusCode();
//var responseString = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
運行測驗時出現此錯誤。
失敗的 amaranth.Tests.AuthTests.Get_ClaimAdminIsReturnedForFirstRegistered [505 ms]
錯誤訊息:
System.Net.Http.HttpRequestException:回應狀態代碼未指示成功:400(錯誤請求)。堆疊跟蹤:
在 System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at amaranth.Tests.AuthTests.Get_ClaimAdminIsReturnedForFirstRegistered() 在 /path/to/dir/amaranth.Tests/IntegrationTests/AuthTests.cs:line 102
--- 堆疊跟蹤結束以前的位置---
如何進行此測驗或撰寫新測驗以確保注冊成功?
更新
如果相關,這是我CustomWebApplicationFactory.cs正在使用的檔案:
using System;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using amaranth.Data;
namespace amaranth.Tests
{
#region snippet1
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup: class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ApplicationDbContext>));
services.Remove(descriptor);
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
});
var sp = services.BuildServiceProvider();
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<ApplicationDbContext>();
var logger = scopedServices
.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();
db.Database.EnsureCreated();
}
});
}
}
#endregion
}
uj5u.com熱心網友回復:
測驗失敗,因為您沒有在 POST 中包含防偽 cookie 和驗證令牌,因此是 400 狀態代碼。從檔案中的這個頁面:
對 SUT 的任何 POST 請求都必須滿足應用程式的資料保護防偽系統自動進行的防偽檢查。為了安排測驗的 POST 請求,測驗應用程式必須:
- 請求頁面。
- 從回應中決議防偽 cookie 并請求驗證令牌。
- 使用防偽 cookie 發出 POST 請求并請求驗證令牌。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483046.html
標籤:C# 网 asp.net-mvc 集成测试 剃刀页面
下一篇:無法將“MySql.Data.MySqlClient.MySqlParameter”型別的物件轉換為“MySqlConnector.MySqlParameter”型別
