The HotChocolate blog gives some guidance on how to write integration tests. This is a good starting point but doesn’t help you get to a final solution when you are using authorization in your GraphQL schema.
In that case you need a way to inject an authenticated ClaimsPrincipal into the GraphQL middleware. It took us some time to figure out a solution but here are the steps involved:
Create custom middleware:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FakeUserMiddleware | |
{ | |
private readonly QueryDelegate _next; | |
public FakeUserMiddleware(QueryDelegate next) | |
{ | |
_next = next ?? throw new ArgumentNullException(nameof(next)); | |
} | |
public Task InvokeAsync(IQueryContext context) | |
{ | |
var claimslist = new List<Claim> { /*Add the list of claims you need*/ }; | |
var claimsPrincipal = new ClaimsPrincipal(); | |
claimsPrincipal.AddIdentity(new ClaimsIdentity(claimslist,"fakeauth")); | |
//The HotChocolate authorization code will search for a claimsprincipal in the ContextData | |
context.ContextData[nameof(ClaimsPrincipal)] = claimsPrincipal; | |
return _next.Invoke(context); | |
} | |
} |
Register middleware:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services.AddGraphQL(Schema.Create(c => | |
{ | |
c.RegisterQueryType<Query>(); | |
}) | |
.MakeExecutable(b => b.Use<FakeUserMiddleware>().UseDefaultPipeline())); |