Not sure if AspNetCore changed a lot, but nowadays in Net7 you can simply do this
someController.ControllerContext.HttpContext = new DefaultHttpContext { User = new GenericPrincipal(new GenericIdentity(userName) , new []{string.Empty}) };
An example with a working unit test
[Test] public async Task GetAll_WhenUserNotExist_ReturnsNotFound() { // arrange var autoMock = AutoMock.GetLoose(); const string userName = "[email protected]"; var customersServiceMock = autoMock.Mock<ICustomerService>(); customersServiceMock .Setup(service => service.GetAll(userName)).Throws<UserDoesNotExistException>(); var customerController = autoMock.Create<CustomerController>(); // // Create a new DefaultHttpContext and assign a generic identity which you can give a user name customerController.ControllerContext.HttpContext = new DefaultHttpContext { User = new GenericPrincipal(new GenericIdentity(userName) , new []{string.Empty}) }; var httpResult = await customerController.GetAllCustomers() as NotFoundResult; // act Assert.IsNotNull(httpResult); }
The implementation of the controller
[HttpGet] [Route("all")] public async Task<IActionResult> GetAllCustomers() { // User identity name will return harry@potter now. var userName = User.Identity?.Name; try { var customers = await _customerService.GetAll(userName).ConfigureAwait(false); return Ok(customers); } catch (UserDoesNotExistException) { Log.Warn($"User {userName} does not exist"); return NotFound(); } }