简体   繁体   English

单元测试模拟 ControllerContext HttpContext 没有为类型“Microsoft.AspNetCore.Mvc.View...ITempDataDictionaryFactory”注册服务

[英]Unit Tests Mock ControllerContext HttpContext No service for type 'Microsoft.AspNetCore.Mvc.View...ITempDataDictionaryFactory' has been registered

In my test project i am using xUnit with Moq.在我的测试项目中,我将 xUnit 与 Moq 一起使用。

now i want to unit test these piece of code in the controller:现在我想在 controller 中对这些代码进行单元测试:

[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ViewData["ReturnUrl"] = returnUrl;
    return View();
}

As you see it uses the SignOutAsync of the HttpContext .如您所见,它使用HttpContextSignOutAsync

I tried so many solution such as ASP.NET MVC - Unit testing, mocking HttpContext without using any mock framework but didn't work for me, since i dont have access to the HttpRequestBase我尝试了很多解决方案,例如ASP.NET MVC - 单元测试,mocking HttpContext 没有使用任何模拟框架,但对我不起作用,因为我无权访问HttpRequestBase

Using Moq, i am trying to mock this HttpContext , so i tried this:使用 Moq,我试图模拟这个HttpContext ,所以我尝试了这个:

public static Mock<HttpContext> GenerateFakeHttpContext()
{
   var mockHttpContext = new Mock<HttpContext>();
   var authServiceMock = new Mock<IAuthenticationService>();
   authServiceMock.Setup(_ => _.SignOutAsync(
                                   It.IsAny<HttpContext>(), 
                                   It.IsAny<string>(), 
                                   It.IsAny<AuthenticationProperties>()))
       .Returns(Task.FromResult((object)null));

   var serviceProviderMock = new Mock<IServiceProvider>();

   serviceProviderMock.Setup(_ => _.GetService(typeof(IAuthenticationService)))
           .Returns(authServiceMock.Object);

   mockHttpContext.Setup(x => x.RequestServices)
           .Returns(serviceProviderMock.Object);

   return mockHttpContext;
}

inspired from this question: MSTest: Unit Testing HttpContext.SignoutAsync for the logout , after a multiple research.灵感来自这个问题: MSTest: Unit Testing HttpContext.SignoutAsync for the logout ,经过多项研究。

The test method is like this:测试方法是这样的:

public async Task Login_ShouldSignOutToClearCoockies_WhenReturnUrlIsNullOrNotNull()
{
    //Arrange
    _sutAccountController
    .ControllerContext.HttpContext = TestsHelper.GenerateFakeHttpContext().Object;

    //Act
    var result = await _sutAccountController.Login(null);

    //Assert
    result.Should().NotBeNull();
}

but in runtime i get this exception:但在运行时我得到这个异常:

   Duration: 367 ms

  Message: 
System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.

  Stack Trace: 
ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
Controller.get_TempData()
Controller.View(String viewName, Object model)
Controller.View(String viewName)
Controller.View()
AccountController.Login(String returnUrl) line 38
AccountControllerTests.Login_ShouldSignOutToClearCoockies_WhenReturnUrlIsNullOrNotNull() line 46
--- End of stack trace from previous location ---

if there's a better way to mock the HttpContext .如果有更好的方法来模拟HttpContext

Thanks.谢谢。

i finally, found a solution by mocking the controller TempData我终于找到了 mocking controller TempData 的解决方案

Source: Mocking a TempData in ASP.NET Core in MSTest来源: MSTest 中 ASP.NET 核心中的 Mocking TempData

var tempData = new Microsoft.AspNetCore.Mvc.ViewFeatures
.TempDataDictionary(httpContext, Mock.Of<Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataProvider>());
tempData["ReturnUrl"] = "";

_sutController.ControllerContext.HttpContext = httpContext;
_sutController.TempData = tempData

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有注册“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”类型的服务 - No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered 没有注册类型为“Microsoft.AspNetCore.Mvc ...”的服务 - No service for type 'Microsoft.AspNetCore.Mvc..." has been registered ASP.NET 核心 3:InvalidOperationException:没有 Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource 类型的服务已注册 - ASP.NET Core 3: InvalidOperationException: No service for type Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource has been registered 没有注册“Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor”类型的服务 - No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor' has been registered 没有为“Microsoft.AspNetCore.Http.HttpContextAccessor”类型注册服务 - No service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' has been registered 没有注册“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered System.InvalidOperationException:“没有为类型 'Microsoft.AspNetCore.Hosting.Server.IServer' 注册服务。” - System.InvalidOperationException: 'No service for type 'Microsoft.AspNetCore.Hosting.Server.IServer' has been registered.' 没有为“Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]”类型注册服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]' has been registered 没有注册 'Microsoft.AspNetCore.Identity.UserManager`1[System.Model.User]' 类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[System.Model.User]' has been registered 没有注册 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext' 类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext' has been registered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM