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

Flu*_*Owl 5 c# unit-testing asp.net-identity asp.net-core

我试图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 => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));

        services.AddIdentity<ApplicationUser, IdentityRole>(o =>
        {
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 3;
        }).AddEntityFrameworkStores<ApplicationDbContext>();

            // IHttpContextAccessor is required for SignInManager, and UserManager
        var context = new DefaultHttpContext();

        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature { Handler = handler });

        services.AddSingleton<IHttpContextAccessor>(new HttpContextAccessor()
        {
            HttpContext = context
        });

        return services.BuildServiceProvider();
    }

    public Mock<IAuthenticationHandler> MockSignInHandler()
    {
        var handler = new Mock<IAuthenticationHandler>();
        handler.Setup(o => o.AuthenticateAsync(It.IsAny<AuthenticateContext>())).Returns<AuthenticateContext>(c =>
        {
            c.NotAuthenticated();
            return Task.FromResult(0);
        });
        handler.Setup(o => o.SignInAsync(It.IsAny<SignInContext>())).Returns<SignInContext>(c =>
        {
            c.Accept();
            return Task.FromResult(0);
        });

        return handler;
    }
    public void Dispose(){}
}
Run Code Online (Sandbox Code Playgroud)

还有这个:

public class AccountControllerTests : IClassFixture<AccountControllerTestsFixture>
{
    private AccountControllerTestsFixture _fixture;

    public AccountControllerTests(AccountControllerTestsFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public async Task Login_When_Present_Provider_Version()
    {
        // Arrange
        var mockedHandler = _fixture.MockSignInHandler();
        IServiceProvider serviceProvider = _fixture.BuildServiceProvider(mockedHandler.Object);

        var userName = "Flattershy";
        var userPassword = "Angel";
        var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, userName) };

        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var userManagerResult = await userManager.CreateAsync(new ApplicationUser() { Id = userName, UserName = userName, TwoFactorEnabled = false }, userPassword);

        Assert.True(userManagerResult.Succeeded);

        var signInManager = serviceProvider.GetRequiredService<SignInManager<ApplicationUser>>();

        AccountController controller = new AccountController(userManager, signInManager);

        // Act
        var model = new LoginArgumentsModel { UserName = userName, Password = userPassword };
        var result = await controller.Login(model) as Microsoft.AspNetCore.Mvc.StatusCodeResult;

        // Assert
        Assert.Equal((int)System.Net.HttpStatusCode.OK, result.StatusCode);
    }

}
Run Code Online (Sandbox Code Playgroud)

多个模拟IAuthenticationHandler和创建IAuthenticationHandler以不同方式为每个测试实现的多个类对我来说看起来有点太过分了,但我也想使用serviceProvider并且不想模拟userManagersignInManager.虽然以这种方式编写的测试似乎有效但我想知道是否有任何不复杂的使用方式CookieAuthenticationHandler或其他任何与应用程序相同的方式app.UseIdentity().

Hao*_*ung 0

您是否可以模拟 SignInManager,将其粘贴到服务集合中,然后设置一次调用以_signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false)返回您想要为控制器测试的结果?