0

I am trying to Unit Test the code below.

    public async Task<AppErrorCountByDateListVm> GetAppErrorCountByDateAsync()
    {
       var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
            if (accessToken != null)
            {
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            }  
...

Specially I want to moq / set up: _httpContextAccessor.HttpContext.GetTokenAsync

Below is my Unit Test:

        private IErrorLogService _sut;

        private Mock<HttpClient> _httpClient;
        private Mock<IHttpContextAccessor> _httpContextAccessor;
        private Mock<IJsonSerializerUtility> _jsonSerializerUtility;

        [SetUp]
        public void RunBeforeEachTest()
        {
            _httpClient = new Mock<HttpClient>();
            _httpContextAccessor = new Mock<IHttpContextAccessor>();
            _jsonSerializerUtility = new Mock<IJsonSerializerUtility>();

            _sut = new ErrorLogService(_httpClient.Object, _httpContextAccessor.Object, _jsonSerializerUtility.Object);
        }

        [Test]
        public async Task OnInitializedAsyncTest()
        {
            //Arrange
            _httpContextAccessor.Setup(h => h.HttpContext.GetTokenAsync("access_token")).ReturnsAsync(It.IsAny<string>());

            //Act
            await _sut.GetAppErrorCountByDateAsync();

            //Assert
        }

I am getting the following error messages:

System.NotSupportedException : Unsupported expression: ... => ....GetTokenAsync("access_token")
Extension methods (here: AuthenticationHttpContextExtensions.GetTokenAsync) may not be used in setup / verification expressions.

I assume I am missing a few steps.

Any help would be appreciated.

Richard
  • 1,054
  • 1
  • 19
  • 36

1 Answers1

0

The error you getting is because you are trying to mock a static method (extension method). And you can't do that, at least not with the framework you are using.

I have faced the same problem, and I just wrapped it up. Let me explain... Create a wrapper object on HttpContext, with that you'll be able to mock "GetTokenAsync".

See this Memoires of a http request - How I got unit tested, it has a good example of this exact problem.

Of course, there are other ways to mock Static methods, have a look at Mocking Extension Methods with Moq

Yassine
  • 35
  • 7
  • Thank you for responding. I got away from this issue for a little while but I am back on it. For some reason the original code that I wanted to unit test did not copy over correctly so I updated that section. I spent sometime trying some of your ideas but I don't get it. I don't understand how can wrap up HttpContext when it is a property off of HttpContextAccessor. Sorry that I am being a little thick. I just don't get it. Can you give me some more hints. Thanks @Yassine – Richard Apr 14 '20 at 15:08