Unit Testing
In most cases, there's no need to set up additional components for running tests. But if the component being tested uses HttpRuntime, it might be necessary to start up the SystemWebAdapters
service, as shown in the following example:
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);
}
}
The tests must be executed in sequence, not in parallel. The preceding example illustrates how to achieve this by setting XUnit's DisableParallelization
option to true
. This setting disables parallel execution for a specific test collection, ensuring that the tests within that collection run one after the other, without concurrency.
Met ons samenwerken op GitHub
De bron voor deze inhoud vindt u op GitHub, waar u ook problemen en pull-aanvragen kunt maken en controleren. Bekijk onze gids voor inzenders voor meer informatie.