|
| 1 | +# Integrating with TUnit |
| 2 | + |
| 3 | +Like other testing frameworks, you'll want to reuse the `IAlbaHost` across tests and test fixtures because |
| 4 | +`AlbaHost` is relatively expensive to create. To do that with TUnit, you should start by writing a bootstrapping class |
| 5 | + that inherits from `IAsyncInitializer` and `IAsyncDisposable`: |
| 6 | + |
| 7 | +<!-- snippet: sample_TUnit_Application --> |
| 8 | +<a id='snippet-sample_tunit_application'></a> |
| 9 | +```cs |
| 10 | +public sealed class AlbaBootstrap : IAsyncInitializer, IAsyncDisposable |
| 11 | +{ |
| 12 | + public IAlbaHost Host { get; private set; } = null!; |
| 13 | + |
| 14 | + public async Task InitializeAsync() |
| 15 | + { |
| 16 | + Host = await AlbaHost.For<WebApp.Program>(); |
| 17 | + } |
| 18 | + |
| 19 | + public async ValueTask DisposeAsync() |
| 20 | + { |
| 21 | + await Host.DisposeAsync(); |
| 22 | + } |
| 23 | +} |
| 24 | +``` |
| 25 | +<sup><a href='https://github.com/JasperFx/alba/blob/master/src/TUnitSamples/Program.cs#L6-L21' title='Snippet source file'>snippet source</a> | <a href='#snippet-sample_tunit_application' title='Start of snippet'>anchor</a></sup> |
| 26 | +<!-- endSnippet --> |
| 27 | + |
| 28 | +Then inject the instance by added `[ClassDataSource<AlbaBootstrap>(Shared = SharedType.Globally)]` to your test class. We recommend creating a base class to allow easier access of the host and any other dependencies. |
| 29 | + |
| 30 | +<!-- snippet: sample_TUnit_scenario_test --> |
| 31 | +<a id='snippet-sample_tunit_scenario_test'></a> |
| 32 | +```cs |
| 33 | +public abstract class AlbaTestBase(AlbaBootstrap albaBootstrap) |
| 34 | +{ |
| 35 | + protected IAlbaHost Host => albaBootstrap.Host; |
| 36 | +} |
| 37 | + |
| 38 | +[ClassDataSource<AlbaBootstrap>(Shared = SharedType.Globally)] |
| 39 | +public class MyTestClass(AlbaBootstrap albaBootstrap) : AlbaTestBase(albaBootstrap) |
| 40 | +{ |
| 41 | + [Test] |
| 42 | + public async Task happy_path() |
| 43 | + { |
| 44 | + await Host.Scenario(_ => |
| 45 | + { |
| 46 | + _.Get.Url("/fake/okay"); |
| 47 | + _.StatusCodeShouldBeOk(); |
| 48 | + }); |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
| 52 | +<sup><a href='https://github.com/JasperFx/alba/blob/master/src/TUnitSamples/Program.cs#L23-L42' title='Snippet source file'>snippet source</a> | <a href='#snippet-sample_tunit_scenario_test' title='Start of snippet'>anchor</a></sup> |
| 53 | +<!-- endSnippet --> |
0 commit comments