简体   繁体   中英

Integration test with Hotchocolate GraphQL and TestServer in C#

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, eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM