Integration test with Hotchocolate GraphQL and TestServer in C#

Viewed 852

I have an ASP.NET Core Api (.NET 6.0) with REST- and GraphQL-endpoints. The GraphQL-endpoints are implemented with Hotchocolate (12.6.0).

For testing the REST endpoints I create a TestServer like this:

protected static async Task<TestServer> CreateServer()
{
     IHostBuilder webHostBuilder = new HostBuilder();
     webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());

     webHostBuilder.ConfigureWebHost(webBuilder =>
          {
               webBuilder
                    .UseTestServer()
                    .UseEnvironment("Test")
                    .ConfigureAppConfiguration((_, config) =>    
                         config.AddJsonFile("appsettings.Test.json"))
                    .UseStartup<AuthenticatedTestStartup>();
           });

     IHost host = await webHostBuilder.StartAsync();
     return host.GetTestServer();
}

AuthenticatedTestStartup derives from Startup and overrides some methods there, e.g. the database configuration. Using the test server created above I can perform integration tests by using the .CreateClient() method which returns an HttpClient object. With thìs client I am able to call the REST endpoints. This works very fine.

My question is now: Is there a way to use this test server for integration tests agains the GraphQL endpoints and if yes: how? If not: What are the alternatives to test the GraphQL endpoints programatically against a test database?

1 Answers

As GraphQL is server over HTTP you can test it the same way as an normal REST endpoint.

But if you do not need HTTP for your tests I would recommend to use a in memory server as it is way faster.

// arrange
var executor = await new ServiceCollection()
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .BuildRequestExecutorAsync();

// act
var query = QueryRequestBuilder.New()
  .SetQuery("{ foo }")
  // you can also add a test principal if you want to test authorised
  // resolvers
  .AddProperty(nameof(ClaimsPrincipal), CreatePrincipal())
  .Create()
var result = executor.ExecuteAsync(query);

// assert
// assert here
Related