ASP.NET Web API: Mock authorization, headers in Unit Test

Jayakumar vinayagam 1 Reputation point
2021-07-20T06:40:57.303+00:00

Hi All,

I have to mock the authorization and headers while calling controller action in the Unit test method.

ValueController.cs ( ASP.Net Web Api(.Net Framework 4.6.1)

Public async Task<HttpResponseMessage> ValueProcessMessageAsync()
{
HttpResponseMessage response = new HttpResponseMessage();
try
{

                 string user = Decode(Request.Headers.Authorization.Parameter);
                 string clientName= HttpContext.Current.Request.Headers["ClientName"];
                 response.StatusCode = HttpStatusCode.OK;
                 return response;              
             }
            catch (Exception)
            { 

                response.StatusCode = HttpStatusCode.InternalServerError;
                return response;             
             }

}

Unit Test:

I can mock the service and Repository layer by using the MOQ framework and do the same in the header request validation.

Help me to mock Headers and Authorization while calling GET/POST/DELETE/PUT action methods in ASP.NET Web API

Thanks,

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
306 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,966 Reputation points
    2021-07-21T15:14:44.933+00:00

    you should design your code to be testable. if you have difficult mocking, then the code is not properly designed.

    your code should not access headers directly. it should call a service instead to access the headers (why should the code know headers are used?). then you can mock the service,

    0 comments No comments