Asp.net core authorization check in tests


  • Junior Test Automation

    Let's say I created a blank asp.net core 2.1 application and added [Authorize] to the About action.

    How can I check in unit tests that the Index page is served to non-logged in users, and the About page began to require authorization?


  • QA Engineer

    In order to check that the page is available under a non-logged in user, it is enough to make sure that the response code will be 2xx:

    [TestFixture]
    public class HomeControllerTest
    {
        public HomeControllerTest ()
        {
            this._factory = new CustomWebApplicationFactory <Startup> ();
        }
    
        private readonly WebApplicationFactory <Startup> _factory;
    
        [Test]
        public async Task IndexPage_ForNonLoggedUser_ReturnsPageContent ()
        {
            // Arrange
            var client = this._factory.CreateClient ();
    
            // Act
            var response = await client.GetAsync ("/");
    
            // Assert
            response.EnsureSuccessStatusCode (); // Status Code 200-299
        }
    }
    

    But checking that the page is available under an authorized user is more complicated: you need to turn off automatic redirection in the client and check that we are redirected to the authorization page.

    [Test]
    public async Task AboutPage_ForNonLoggedUser_RedirectsToLoginPages ()
    {
        // Arrange
        var client = this._factory.CreateClient (
            new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });
    
        // Act
        var response = await client.GetAsync ("/ Home / About");
    
        // Assert
        Assert.AreEqual (HttpStatusCode.Redirect, response.StatusCode);
        StringAssert.StartsWith ("http: // localhost / Identity / Account / Login", response.Headers.Location.OriginalString);
    }
    

    (I saw examples on the net in which the 403 response was checked, maybe this worked for earlier versions of asp.net core, I just need a redirect check on 2.1)

    Exactly the same tests are required for Razor Page, they are nothing different from similar checks.

    Basically, there is a detailed description in the documentation, and there is also a link to a test application with xUnit.



Suggested Topics