0

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)

ShaneKm
  • 20,823
  • 43
  • 167
  • 296
  • 1
    You can see this [thread](https://stackoverflow.com/questions/47198341/how-to-unit-test-httpcontext-signinasync) may helpful. – Yinqiu Mar 05 '21 at 06:54
  • yep, that worked. thanks much. @Yingiu please post your comment as an answer. – ShaneKm Mar 05 '21 at 16:53

1 Answers1

1

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.

Yinqiu
  • 6,609
  • 1
  • 6
  • 14