小编Flu*_*Owl的帖子

如何在单元测试ASP.NET Core控制器时正确模仿IAuthenticationHandler

我试图Login在我AccountControllerMusiStore示例中基于测试对我这样的简单方法进行单元测试.

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginArgumentsModel model)
{
   if (!ModelState.IsValid)
   {
      return BadRequest();
   }
   var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
   if (result.Succeeded)
   {
      return Ok();
   }
return StatusCode(422); // Unprocessable Entity
}
Run Code Online (Sandbox Code Playgroud)

为此,我需要使用两者UserManager,SignInManager并最终迫使我使用写替代IAuthenticationHandler使用HttpAuthenticationFeature.最后的测试结果如下:

public class AccountControllerTestsFixture : IDisposable
{
    public IServiceProvider BuildServiceProvider(IAuthenticationHandler handler)
    {
        var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();

        var services = new ServiceCollection();
        services.AddOptions();
        services.AddDbContext<ApplicationDbContext>(b …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing asp.net-identity asp.net-core

5
推荐指数
1
解决办法
673
查看次数

标签 统计

asp.net-core ×1

asp.net-identity ×1

c# ×1

unit-testing ×1