ShaneKm
ShaneKm

Reputation: 21308

DefaultHttpContext testing authentication in integration tests

Trying to run some integration tests and using DefaultHttpContext in my unit and integration tests. Is there a way to call SignInAsync() on DefaultHttpContext?

        var claims = new List<Claim>();
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties
        {
            AllowRefresh = true,
            IsPersistent = true,
            IssuedUtc = DateTime.UtcNow
        };

        await _controller.HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

Running above throws an exception when using DefaultHttpContext for some reason:

System.ArgumentNullException : Value cannot be null. (Parameter 'provider') at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)

Upvotes: 0

Views: 573

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

You can either create a fake/mock manually by creating classes that derive from the used interfaces or use a mocking framework like Moq.

Referenced with this thread.

Upvotes: 1

Related Questions