HttpContext
在这种特殊情况下,确实没有必要模拟。
使用DefaultHttpContext
和设置完成测试所需的成员
例如
[Theory] [MemberData(nameof(TestCreateUsergroupItemData))] public async Task TestPostUsergroupItem(Usergroup usergroup) { // Arrange //... var identity = new GenericIdentity("some name", "test"); var contextUser = new ClaimsPrincipal(identity); //add claims as needed //...then set user and other required properties on the httpContext as needed var httpContext = new DefaultHttpContext() { User = contextUser; }; //Controller needs a controller context to access HttpContext var controllerContext = new ControllerContext() { HttpContext = httpContext, }; //assign context to controller UsergroupController controller = new UsergroupController(context, mapper) { ControllerContext = controllerContext, }; // Act var controllerResult = await controller.Post(usergroup).ConfigureAwait(false); // Assert .... }