使用 C# 中的测试服务器确定对 Xunit 测试的依赖关系

问题描述 投票:0回答:1

我使用 c# 测试服务器来做一些测试,但我必须为每个 Xunit Fact 启动一个新的测试服务器。这是因为我有一些假的实现,假的持久性,甚至数据模糊有时,如果服务器是共享的,它们也会发生冲突。此外,测试套件不断增长并且开始需要时间。 所以我想知道有人成功地使用了测试服务器并限制了对 Xunit Fact LifeCycle 的依赖?

c# asp.net dependency-injection xunit.net testserver
1个回答
0
投票

是的,您可以通过在 xUnit 测试生命周期内管理依赖项的生命周期来实现这一点。 xUnit 提供了多个固定装置和生命周期挂钩,您可以使用它们来控制资源的设置和拆卸,包括测试服务器及其依赖项。

一种常见的方法是使用测试夹具来管理共享资源(例如测试服务器)的生命周期。然后,您可以在夹具的设置方法(xUnit 中的ctor)中配置测试服务器,并在拆卸方法(xUnit 中的Dispose())中对其进行处理。此外,您可以使用构造函数注入将测试服务器或其他依赖项注入到您的测试类中。

例如,您可以通过以下方式使用 xUnit 夹具构建测试:

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Xunit;

//TestServerFixture is a fixture class responsible for setting up and tearing down the test server.
//The TestServerFixture sets up the test server in its constructor and disposes of it when Dispose() is called.
public class TestServerFixture : IDisposable
{
    public TestServer Server { get; private set; }

    public TestServerFixture()
    {
        // Configure and start the test server
        var builder = new WebHostBuilder().UseStartup<Startup>();
        Server = new TestServer(builder);
    }

    public void Dispose()
    {
        // Dispose of the test server when the fixture is disposed
        Server.Dispose();
    }
}

//MyTestClass is a test class that uses the TestServerFixture as a fixture by implementing IClassFixture.
public class MyTestClass : IClassFixture<TestServerFixture>
{
    private readonly TestServerFixture _fixture;

    public MyTestClass(TestServerFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public void Test1()
    {
        // Use the test server in your test
        var client = _fixture.Server.CreateClient();
        // Perform test actions
    }

    [Fact]
    public void Test2()
    {
        // Use the test server in another test
        var client = _fixture.Server.CreateClient();
        // Perform test actions
    }
}
  • TestServerFixture是一个fixture类,负责设置和拆除测试服务器。
  • MyTestClass 是一个测试类,通过实现 IClassFixture 使用 TestServerFixture 作为固定装置。
  • MyTestClass中的每个测试方法都会通过构造函数注入接收TestServerFixture的实例。
  • TestServerFixture 在其构造函数中设置测试服务器,并在调用 Dispose() 时将其释放。

通过使用这种方法,您可以确保每个测试方法都有自己的测试服务器实例,范围仅限于测试类的生命周期。这使您可以隔离测试并更有效地管理依赖关系。

© www.soinside.com 2019 - 2024. All rights reserved.