单元测试
在大多数情况下,无需设置用于运行测试的其他组件。 但是,如果测试的组件使用 HttpRuntime,则可能需要启动 SystemWebAdapters
服务,如以下示例所示:
namespace TestProject1;
/// <summary>
/// This demonstrates an xUnit feature that ensures all tests
/// in classes marked with this collection are run sequentially.
/// </summary>
[CollectionDefinition(nameof(SystemWebAdaptersHostedTests),
DisableParallelization = true)]
public class SystemWebAdaptersHostedTests
{
}
[Collection(nameof(SystemWebAdaptersHostedTests))]
public class RuntimeTests
{
/// <summary>
/// This method starts up a host in the background that
/// makes it possible to initialize <see cref="HttpRuntime"/>
/// and <see cref="HostingEnvironment"/> with values needed
/// for testing with the <paramref name="configure"/> option.
/// </summary>
/// <param name="configure">
/// Configuration for the hosting and runtime options.
/// </param>
public static async Task<IDisposable> EnableRuntimeAsync(
Action<SystemWebAdaptersOptions>? configure = null,
CancellationToken token = default)
=> await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSystemWebAdapters();
if (configure is not null)
{
services.AddOptions
<SystemWebAdaptersOptions>()
.Configure(configure);
}
})
.Configure(app =>
{
// No need to configure pipeline for tests
});
})
.StartAsync(token);
[Fact]
public async Task RuntimeEnabled()
{
using (await EnableRuntimeAsync(options =>
options.AppDomainAppPath = "path"))
{
Assert.True(HostingEnvironment.IsHosted);
Assert.Equal("path", HttpRuntime.AppDomainAppPath);
}
Assert.False(HostingEnvironment.IsHosted);
}
}
测试必须按顺序执行,而不是并行执行。 前面的示例演示如何通过将 XUnitDisableParallelization
的选项设置为 true
来实现此目的。 此设置禁用特定测试集合的并行执行,确保该集合中的测试一个接一个运行,而无需并发。