简体   繁体   English

在 C# 中使用 Hotchocolate GraphQL 和 TestServer 进行集成测试

[英]Integration test with Hotchocolate GraphQL and TestServer in C#

I have an ASP.NET Core Api (.NET 6.0) with REST- and GraphQL-endpoints.我有一个带有 REST 和 GraphQL 端点的 ASP.NET Core Api (.NET 6.0)。 The GraphQL-endpoints are implemented with Hotchocolate (12.6.0). GraphQL 端点是用 Hotchocolate (12.6.0) 实现的。

For testing the REST endpoints I create a TestServer like this:为了测试 REST 端点,我创建了一个这样的TestServer

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. AuthenticatedTestStartup派生自Startup并覆盖那里的一些方法,例如数据库配置。 Using the test server created above I can perform integration tests by using the .CreateClient() method which returns an HttpClient object.使用上面创建的测试服务器,我可以使用返回HttpClient object 的.CreateClient()方法执行集成测试。 With thìs client I am able to call the REST endpoints.有了这个客户端,我可以调用 REST 端点。 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?我现在的问题是:有没有办法使用此测试服务器对 GraphQL 端点进行集成测试,如果是:如何? If not: What are the alternatives to test the GraphQL endpoints programatically against a test database?如果不是:针对测试数据库以编程方式测试 GraphQL 端点的替代方法是什么?

As GraphQL is server over HTTP you can test it the same way as an normal REST endpoint.由于 GraphQL 是 HTTP 之上的服务器,因此您可以像普通 REST 端点一样对其进行测试。

But if you do not need HTTP for your tests I would recommend to use a in memory server as it is way faster.但是,如果您不需要 HTTP 进行测试,我建议您使用 memory 服务器,因为它更快。

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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