How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

后端 未结 4 2224

Lets say I am setting a value on the http context in my middleware. For example HttpContext.User.

How can test the http context in my unit test. Here is an example o

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 08:56

    It would be better if you unit test your middleware class in isolation from the rest of your code.

    Since HttpContext class is an abstract class, you can use a mocking framework like Moq (adding "Moq": "4.2.1502.911", as a dependency to your project.json file) to verify that the user property was set.

    For example you can write the following test that verifies your middleware Invoke function is setting the User property in the httpContext and calling the next middleware:

    [Fact]
    public void MyAuthMiddleware_SetsUserAndCallsNextDelegate()
    {
        //Arrange
        var httpContextMock = new Mock()
                .SetupAllProperties();
        var delegateMock = new Mock();
        var sut = new MyAuthMiddleware(delegateMock.Object);
    
        //Act
        sut.Invoke(httpContextMock.Object).Wait();
    
        //Assert
        httpContextMock.VerifySet(c => c.User = It.IsAny(), Times.Once);
        delegateMock.Verify(next => next(httpContextMock.Object), Times.Once);
    }
    

    You could then write additional tests for verifying the user has the expected values, since you will be able to get the setted User object with httpContextMock.Object.User:

    Assert.NotNull(httpContextMock.Object.User);
    //additional validation, like user claims, id, name, roles
    

提交回复
热议问题