Search code examples
c#.nethotchocolate

Mocking Authentication in .Net with IRequestExecutor


Trying to write some integration tests for the first time in .NET - specifically for HotChocolate.

I’ve got had tests working with the WebApplicationFactory, the final part left is trying to now mock the authentication. I tried to set it up based on Mock Authentication but I’m querying the data with IRequestExecutor and finding the de-facto way of setting it up doesn't actually fire:

        [Fact]
        public async Task GetJokes()
        {
            var query =
                @"query Jokes {
                  jokes(jokeLength: SMALL) {
                    nodes {
                      id
                      body
                    }
                  }
                }";
            
            var request = QueryRequestBuilder.New().SetQuery(query).Create();
            var executor = await _factory.Services.GetRequestExecutorAsync();
            var result = await executor.ExecuteAsync(request);
            (await result.ToJsonAsync()).MatchSnapshot();
        }

When I debug this I never hit HandleAuthenticateAsync in my AuthHandler’s (setup from the Mock Authentication linked above), so the claims are never added - so looks like those only run for the httpClient requests - is there a way to configure the IRequestExecutor to be authenticated too?


Solution

  • You can add the ClaimsPrincipal directly as property to the QueryRequestBuilder.

    var request = QueryRequestBuilder
    .New()
    .SetQuery(query)
    .AddProperty(nameof(ClaimsPrincipal), new ClaimsPrincipal(new ClaimsIdentity("test")))
    .Create();