Mock HttpRequest in ASP.NET Core Controller

前端 未结 1 1330
时光说笑
时光说笑 2020-12-15 04:05

I\'m building a Web API in ASP.NET Core, and I want to unit test the controllers.

I inject an interface for data access, that I can easily mock. But the controller

相关标签:
1条回答
  • 2020-12-15 04:43

    When creating an instance of the controller under test, make sure to assign a HttpContext that contains the required dependencies for the test to be exercised to completion.

    You could try mocking a HttpContext and providing that to the controller or just use DefaultHttpContext provided by the framework

    //Arrange
    var mockedAccessor = new Mock<IAccessor>();
    //...setup mockedAccessor behavior
    
    //...
    
    var httpContext = new DefaultHttpContext(); // or mock a `HttpContext`
    httpContext.Request.Headers["token"] = "fake_token_here"; //Set header
     //Controller needs a controller context 
    var controllerContext = new ControllerContext() {
        HttpContext = httpContext,
    };
    //assign context to controller
    var controller = new PlayersController (mockedAccessor.Object){
        ControllerContext = controllerContext,
    };
    
    //Act
    var result = controller.Get();
    
    //...
    

    The above assumes you already know how to mock the controller dependencies like IAccessor and was meant to demonstrate how to provide framework specific dependencies needed for the test.

    0 讨论(0)
提交回复
热议问题