Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.
TUnit Advanced Applications: Data-Driven Testing, Dependency Injection, and Integration Testing
Applicable Scenarios
This skill covers TUnit advanced application techniques, from data-driven testing to dependency injection, from
execution control to ASP.NET Core integration testing practice.
Core Topics
- Data-driven testing advanced techniques (MethodDataSource, ClassDataSource, Matrix Tests)
- Properties attribute marking and test filtering
- Test lifecycle and dependency injection
- Execution control (Retry, Timeout, DisplayName)
- ASP.NET Core integration testing (WebApplicationFactory)
- Performance testing and load testing
- TUnit + Testcontainers complex infrastructure orchestration
- TUnit Engine Modes and troubleshooting
Data-Driven Testing Advanced Techniques
TUnit provides MethodDataSource, ClassDataSource, and Matrix Tests as three advanced data sources. MethodDataSource is
most flexible, supporting dynamic generation and external file loading; ClassDataSource is suitable for cross-test class
data sharing and AutoFixture integration; Matrix Tests automatically generates all parameter combinations (note: control
quantity to avoid explosive growth).
Full examples and comparison table please refer to
references/data-driven-testing.md
Properties Attribute Marking and Test Filtering
Basic Properties Usage
[Test]
[Property("Category", "Database")]
[Property("Priority", "High")]
public async Task DatabaseTest_HighPriority_ShouldBeFilterableByAttribute()
{
await Assert.That(true).IsTrue();
}
[Test]
[Property("Category", "Unit")]
[Property("Priority", "Medium")]
public async Task UnitTest_MediumPriority_BasicValidation()
{
await Assert.That(1 + 1).IsEqualTo(2);
}
[Test]
[Property("Category", "Integration")]
[Property("Priority", "Low")]
[Property("Environment", "Development")]
public async Task IntegrationTest_LowPriority_OnlyRunInDevEnvironment()
{
await Assert.That("Hello World").Contains("World");
}
```text
### Establishing Consistent Attribute Naming Conventions
```csharp
public static class TestProperties
{
// Test categories
public const string CATEGORY_UNIT = "Unit";
public const string CATEGORY_INTEGRATION = "Integration";
public const string CATEGORY_E2E = "E2E";
// Priority levels
public const string PRIORITY_CRITICAL = "Critical";
public const string PRIORITY_HIGH = "High";
public const string PRIORITY_MEDIUM = "Medium";
public const string PRIORITY_LOW = "Low";
// Environments
public const string ENV_DEVELOPMENT = "Development";
public const string ENV_STAGING = "Staging";
public const string ENV_PRODUCTION = "Production";
}
[Test]
[Property("Category", TestProperties.CATEGORY_UNIT)]
[Property("Priority", TestProperties.PRIORITY_HIGH)]
public async Task ExampleTest_UsingConstants_EnsuresConsistency()
{
await Assert.That(1 + 1).IsEqualTo(2);
}
```text
### TUnit Test Filtering Execution
TUnit uses `dotnet run` instead of `dotnet test`:
```bash
# Only run unit tests
dotnet run --treenode-filter "/*/*/*/*[Category=Unit]"
# Only run high priority tests
dotnet run --treenode-filter "/*/*/*/*[Priority=High]"
# Combined conditions: run high priority unit tests
dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)&(Priority=High)]"
# OR condition: run unit tests or smoke tests
dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)|(Suite=Smoke)]"
# Run tests for specific features
dotnet run --treenode-filter "/*/*/*/*[Feature=OrderProcessing]"
```text
### Filter Syntax Notes
- Path pattern `/*/*/*/*` represents Assembly/Namespace/Class/Method level
- Attribute names are case-sensitive
- Combined conditions must be properly enclosed in parentheses
---
## Test Lifecycle Management
TUnit provides complete lifecycle hooks: `[Before(Class)]` -> Constructor -> `[Before(Test)]` -> Test Method -> `[After(Test)]` -> Dispose -> `[After(Class)]`. Also has Assembly/TestSession level and `[BeforeEvery]`/`[AfterEvery]` global hooks. Constructor always executes first, BeforeClass/AfterClass each only executes once.
> Full attribute family and examples please refer to [references/lifecycle-management.md](references/lifecycle-management.md)
---
## Dependency Injection Patterns
### TUnit Dependency Injection Core Concepts
TUnit's dependency injection is built on Data Source Generators:
```csharp
public class MicrosoftDependencyInjectionDataSourceAttribute : DependencyInjectionDataSourceAttribute<IServiceScope>
{
private static readonly IServiceProvider ServiceProvider = CreateSharedServiceProvider();
public override IServiceScope CreateScope(DataGeneratorMetadata dataGeneratorMetadata)
{
return ServiceProvider.CreateScope();
}
public override object? Create(IServiceScope scope, Type type)
{
return scope.ServiceProvider.GetService(type);
}
private static IServiceProvider CreateSharedServiceProvider()
{
return new ServiceCollection()
.AddSingleton<IOrderRepository, MockOrderRepository>()
.AddSingleton<IDiscountCalculator, MockDiscountCalculator>()
.AddSingleton<IShippingCalculator, MockShippingCalculator>()
.AddSingleton<ILogger<OrderService>, MockLogger<OrderService>>()
.AddTransient<OrderService>()
.BuildServiceProvider();
}
}
```text
### Using TUnit Dependency Injection
```csharp
[MicrosoftDependencyInjectionDataSource]
public class DependencyInjectionTests(OrderService orderService)
{
[Test]
public async Task CreateOrder_UsingTUnitDependencyInjection_ShouldWorkCorrectly()
{
// Arrange - dependencies automatically injected through TUnit DI
var items = new List<OrderItem>
{
new() { ProductId = "PROD001", ProductName = "Test Product", UnitPrice = 100m, Quantity = 2 }
};
// Act
var order = await orderService.CreateOrderAsync("CUST001", CustomerLevel.VIP, items);
// Assert
await Assert.That(order).IsNotNull();
await Assert.That(order.CustomerId).IsEqualTo("CUST001");
await Assert.That(order.CustomerLevel).IsEqualTo(CustomerLevel.VIP);
}
[Test]
public async Task TUnitDependencyInjection_ValidateAutoInjection_ServiceShouldBeCorrectType()
{
await Assert.That(orderService).IsNotNull();
await Assert.That(orderService.GetType().Name).IsEqualTo("OrderService");
}
}
```text
### TUnit DI vs Manual Dependency Creation Comparison
| Feature | TUnit DI | Manual Dependency Creation |
| :------ | :------- | :------------------------- |
| **Setup Complexity** | Setup once, reuse | Manual creation needed for each test |
| **Maintainability** | Dependency changes only in one place | Need to modify all tests that use it |
| **Consistency** | Consistent with production code DI | May be inconsistent with actual application |
| **Test Readability** | Focus on test logic | Interfered by dependency creation code |
| **Scope Management** | Automatic service scope management | Need to manually manage object lifecycle |
| **Error Risk** | Framework guarantees correct injection | May miss or incorrectly create dependencies |
---
## Execution Control and Test Quality
- **`[Retry(n)]`**: Only for unstable tests caused by external dependencies (network, file locking), not for logic errors
- **`[Timeout(ms)]`**: Set reasonable upper limit for performance-sensitive tests, validate SLA with `Stopwatch`
- **`[DisplayName]`**: Supports `{0}` parameter interpolation, making test reports more business-language aligned
> Full examples (Retry/Timeout/DisplayName) please refer to [references/execution-control.md](references/execution-control.md)
---
## ASP.NET Core Integration Testing
Using `WebApplicationFactory<Program>` in TUnit for ASP.NET Core integration testing, managing lifecycle through `IDisposable` implementation. Covers API response validation, Content-Type header checking, and performance baseline and parallel load testing.
> Full WebApplicationFactory integration and load testing examples please refer to [references/aspnet-integration.md](references/aspnet-integration.md)
---
## TUnit + Testcontainers Infrastructure Orchestration
Using `[Before(Assembly)]` / `[After(Assembly)]` at Assembly level to manage multi-container orchestration for PostgreSQL, Redis, Kafka, combined with `NetworkBuilder` to create shared network. Containers only start once, significantly reducing startup time and resource consumption while maintaining data isolation between tests.
> Full multi-container orchestration and global sharing examples please refer to [references/tunit-testcontainers.md](references/tunit-testcontainers.md)
---
## TUnit Engine Modes
### Source Generation Mode (Default Mode)
```text
████████╗██╗ ██╗███╗ ██╗██╗████████╗
╚══██╔══╝██║ ██║████╗ ██║██║╚══██╔══╝
██║ ██║ ██║██╔██╗ ██║██║ ██║
██║ ██║ ██║██║╚██╗██║██║ ██║
██║ ╚██████╔╝██║ ╚████║██║ ██║
╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝
Engine Mode: SourceGenerated
```text
### Features and Advantages
- **Compile-time generation**: All test discovery logic generated at compile time, no runtime reflection needed
- **Excellent performance**: Several times faster than reflection mode
- **Type safety**: Compile-time validation of test configuration and data sources
- **AOT compatible**: Fully supports Native AOT compilation
### Reflection Mode
```bash
# Enable reflection mode
dotnet run -- --reflection
# Or set environment variable
$env:TUNIT_EXECUTION_MODE = "reflection"
dotnet run
```text
### Applicable Scenarios
- Dynamic test discovery
- F# and VB.NET projects (automatically used)
- Certain reflection-dependent test patterns
### Native AOT Support
```xml
<PropertyGroup>
<PublishAot>true</PublishAot>
</PropertyGroup>
```text
```bash
dotnet publish -c Release
```text
---
## Common Issues and Troubleshooting
### Test Statistics Display Abnormal Issue
**Problem:** `Test Summary: Total: 0, Failed: 0, Success: 0`
### Solution Steps
1. **Ensure project file is correctly configured:**
```xml
<PropertyGroup>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
```text
2. **Ensure GlobalUsings.cs is correct:**
```csharp
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
global using TUnit.Core;
global using TUnit.Assertions;
global using TUnit.Assertions.Extensions;
```text
3. **Special configuration for integration tests:**
```csharp
// Add at the end of WebApi project's Program.cs
public partial class Program { } // Allow integration tests to access
```text
4. **Clean and rebuild:**
```bash
dotnet clean; dotnet build
dotnet test --verbosity normal
```text
### Source Generator Related Issues
### Issue: Test classes not discoverable
- **Solution**: Ensure project is fully rebuilt (`dotnet clean; dotnet build`)
### Issue: Strange errors at compile time
- **Solution**: Check if other Source Generator packages exist, consider updating to compatible versions
### Diagnostic Options
```ini
# .editorconfig
tunit.enable_verbose_diagnostics = true
```text
```xml
<PropertyGroup>
<TUnitEnableVerboseDiagnostics>true</TUnitEnableVerboseDiagnostics>
</PropertyGroup>
```text
---
## Practical Recommendations
### Data-Driven Testing Selection Strategy
- **MethodDataSource**: Suitable for dynamic data, complex objects, external file loading
- **ClassDataSource**: Suitable for shared data, AutoFixture integration, cross-test class reuse
- **Matrix Tests**: Suitable for combination testing, but control parameter quantity to avoid explosive growth
### Execution Control Best Practices
- **Retry**: Only for truly unstable external dependency tests
- **Timeout**: Set reasonable limits for performance-sensitive tests
- **DisplayName**: Make test reports more business-language aligned
### Integration Testing Strategy
- Use WebApplicationFactory for complete Web API testing
- Use TUnit + Testcontainers to build complex multi-service test environments
- Manage complex dependency relationships through attribute injection system
- Only test actually existing functionality, avoid testing non-existent endpoints
---
## Template Files
| File Name | Description |
| --------- | ----------- |
| [data-source-examples.cs](templates/data-source-examples.cs) | MethodDataSource, ClassDataSource examples |
| [matrix-tests-examples.cs](templates/matrix-tests-examples.cs) | Matrix Tests combination testing examples |
| [lifecycle-di-examples.cs](templates/lifecycle-di-examples.cs) | Lifecycle management and dependency injection examples |
| [execution-control-examples.cs](templates/execution-control-examples.cs) | Retry, Timeout, DisplayName examples |
| [aspnet-integration-tests.cs](templates/aspnet-integration-tests.cs) | ASP.NET Core integration testing examples |
| [testcontainers-examples.cs](templates/testcontainers-examples.cs) | Testcontainers infrastructure orchestration examples |
---
## Reference Resources
### Original Articles
This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:
- **Day 29 - TUnit Advanced Applications: Data-Driven Testing and Dependency Injection Deep Practice**
- Article: https://ithelp.ithome.com.tw/articles/10377970
- Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day29
- **Day 30 - TUnit Advanced Applications - Execution Control and Test Quality and ASP.NET Core Integration Testing**
- Article: https://ithelp.ithome.com.tw/articles/10378176
- Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day30
### TUnit Official Resources
- [TUnit Official Website](https://tunit.dev/)
- [TUnit GitHub Repository](https://github.com/thomhurst/TUnit)
### Advanced Feature Documentation
- [TUnit Method Data Source Documentation](https://tunit.dev/docs/test-authoring/method-data-source)
- [TUnit Class Data Source Documentation](https://tunit.dev/docs/test-authoring/class-data-source)
- [TUnit Matrix Tests Documentation](https://tunit.dev/docs/test-authoring/matrix-tests)
- [TUnit Properties Documentation](https://tunit.dev/docs/test-lifecycle/properties)
- [TUnit Dependency Injection Documentation](https://tunit.dev/docs/test-lifecycle/dependency-injection)
- [TUnit Retrying Documentation](https://tunit.dev/docs/execution/retrying)
- [TUnit Timeouts Documentation](https://tunit.dev/docs/execution/timeouts)
- [TUnit Engine Modes Documentation](https://tunit.dev/docs/execution/engine-modes)
- [TUnit ASP.NET Core Documentation](https://tunit.dev/docs/examples/aspnet)
- [TUnit Complex Test Infrastructure](https://tunit.dev/docs/examples/complex-test-infrastructure-orchestration)
### Testcontainers Related Resources
- [Testcontainers.NET Official Website](https://dotnet.testcontainers.org/)
- [Testcontainers.NET GitHub](https://github.com/testcontainers/testcontainers-dotnet)
1---2name: dotnet-testing-advanced-tunit-advanced-43description: Complete guide for TUnit advanced applications. Use when using TUnit for data-driven testing, dependency injection, or integration testing. Covers MethodDataSource, ClassDataSource, Matrix Tests, Properties filtering. Includes Retry/Timeout control, WebApplicationFactory integration, Testcontainers multi-service orchestration. Keywords: TUnit advanced, TUnit advanced, MethodDataSource, ClassDataSource, Matrix Tests, MatrixDataSource, MicrosoftDependencyInjectionDataSource, Property, Retry, Timeout, data-driven testing, test filtering, WebApplicationFactory TUnit, multi-container orchestration4license: MIT5---67Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.89# TUnit Advanced Applications: Data-Driven Testing, Dependency Injection, and Integration Testing1011## Applicable Scenarios1213This skill covers TUnit advanced application techniques, from data-driven testing to dependency injection, from14execution control to ASP.NET Core integration testing practice.1516### Core Topics1718- Data-driven testing advanced techniques (MethodDataSource, ClassDataSource, Matrix Tests)19- Properties attribute marking and test filtering20- Test lifecycle and dependency injection21- Execution control (Retry, Timeout, DisplayName)22- ASP.NET Core integration testing (WebApplicationFactory)23- Performance testing and load testing24- TUnit + Testcontainers complex infrastructure orchestration25- TUnit Engine Modes and troubleshooting2627---2829## Data-Driven Testing Advanced Techniques3031TUnit provides MethodDataSource, ClassDataSource, and Matrix Tests as three advanced data sources. MethodDataSource is32most flexible, supporting dynamic generation and external file loading; ClassDataSource is suitable for cross-test class33data sharing and AutoFixture integration; Matrix Tests automatically generates all parameter combinations (note: control34quantity to avoid explosive growth).3536> Full examples and comparison table please refer to37> [references/data-driven-testing.md](references/data-driven-testing.md)3839---4041## Properties Attribute Marking and Test Filtering4243### Basic Properties Usage4445````csharp46[Test]47[Property("Category", "Database")]48[Property("Priority", "High")]49public async Task DatabaseTest_HighPriority_ShouldBeFilterableByAttribute()50{51 await Assert.That(true).IsTrue();52}5354[Test]55[Property("Category", "Unit")]56[Property("Priority", "Medium")]57public async Task UnitTest_MediumPriority_BasicValidation()58{59 await Assert.That(1 + 1).IsEqualTo(2);60}6162[Test]63[Property("Category", "Integration")]64[Property("Priority", "Low")]65[Property("Environment", "Development")]66public async Task IntegrationTest_LowPriority_OnlyRunInDevEnvironment()67{68 await Assert.That("Hello World").Contains("World");69}70```text7172### Establishing Consistent Attribute Naming Conventions7374```csharp75public static class TestProperties76{77 // Test categories78 public const string CATEGORY_UNIT = "Unit";79 public const string CATEGORY_INTEGRATION = "Integration";80 public const string CATEGORY_E2E = "E2E";8182 // Priority levels83 public const string PRIORITY_CRITICAL = "Critical";84 public const string PRIORITY_HIGH = "High";85 public const string PRIORITY_MEDIUM = "Medium";86 public const string PRIORITY_LOW = "Low";8788 // Environments89 public const string ENV_DEVELOPMENT = "Development";90 public const string ENV_STAGING = "Staging";91 public const string ENV_PRODUCTION = "Production";92}9394[Test]95[Property("Category", TestProperties.CATEGORY_UNIT)]96[Property("Priority", TestProperties.PRIORITY_HIGH)]97public async Task ExampleTest_UsingConstants_EnsuresConsistency()98{99 await Assert.That(1 + 1).IsEqualTo(2);100}101```text102103### TUnit Test Filtering Execution104105TUnit uses `dotnet run` instead of `dotnet test`:106107```bash108# Only run unit tests109dotnet run --treenode-filter "/*/*/*/*[Category=Unit]"110111# Only run high priority tests112dotnet run --treenode-filter "/*/*/*/*[Priority=High]"113114# Combined conditions: run high priority unit tests115dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)&(Priority=High)]"116117# OR condition: run unit tests or smoke tests118dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)|(Suite=Smoke)]"119120# Run tests for specific features121dotnet run --treenode-filter "/*/*/*/*[Feature=OrderProcessing]"122```text123124### Filter Syntax Notes125126- Path pattern `/*/*/*/*` represents Assembly/Namespace/Class/Method level127- Attribute names are case-sensitive128- Combined conditions must be properly enclosed in parentheses129130---131132## Test Lifecycle Management133134TUnit provides complete lifecycle hooks: `[Before(Class)]` -> Constructor -> `[Before(Test)]` -> Test Method -> `[After(Test)]` -> Dispose -> `[After(Class)]`. Also has Assembly/TestSession level and `[BeforeEvery]`/`[AfterEvery]` global hooks. Constructor always executes first, BeforeClass/AfterClass each only executes once.135136> Full attribute family and examples please refer to [references/lifecycle-management.md](references/lifecycle-management.md)137138---139140## Dependency Injection Patterns141142### TUnit Dependency Injection Core Concepts143144TUnit's dependency injection is built on Data Source Generators:145146```csharp147public class MicrosoftDependencyInjectionDataSourceAttribute : DependencyInjectionDataSourceAttribute<IServiceScope>148{149 private static readonly IServiceProvider ServiceProvider = CreateSharedServiceProvider();150151 public override IServiceScope CreateScope(DataGeneratorMetadata dataGeneratorMetadata)152 {153 return ServiceProvider.CreateScope();154 }155156 public override object? Create(IServiceScope scope, Type type)157 {158 return scope.ServiceProvider.GetService(type);159 }160161 private static IServiceProvider CreateSharedServiceProvider()162 {163 return new ServiceCollection()164 .AddSingleton<IOrderRepository, MockOrderRepository>()165 .AddSingleton<IDiscountCalculator, MockDiscountCalculator>()166 .AddSingleton<IShippingCalculator, MockShippingCalculator>()167 .AddSingleton<ILogger<OrderService>, MockLogger<OrderService>>()168 .AddTransient<OrderService>()169 .BuildServiceProvider();170 }171}172```text173174### Using TUnit Dependency Injection175176```csharp177[MicrosoftDependencyInjectionDataSource]178public class DependencyInjectionTests(OrderService orderService)179{180 [Test]181 public async Task CreateOrder_UsingTUnitDependencyInjection_ShouldWorkCorrectly()182 {183 // Arrange - dependencies automatically injected through TUnit DI184 var items = new List<OrderItem>185 {186 new() { ProductId = "PROD001", ProductName = "Test Product", UnitPrice = 100m, Quantity = 2 }187 };188189 // Act190 var order = await orderService.CreateOrderAsync("CUST001", CustomerLevel.VIP, items);191192 // Assert193 await Assert.That(order).IsNotNull();194 await Assert.That(order.CustomerId).IsEqualTo("CUST001");195 await Assert.That(order.CustomerLevel).IsEqualTo(CustomerLevel.VIP);196 }197198 [Test]199 public async Task TUnitDependencyInjection_ValidateAutoInjection_ServiceShouldBeCorrectType()200 {201 await Assert.That(orderService).IsNotNull();202 await Assert.That(orderService.GetType().Name).IsEqualTo("OrderService");203 }204}205```text206207### TUnit DI vs Manual Dependency Creation Comparison208209| Feature | TUnit DI | Manual Dependency Creation |210| :------ | :------- | :------------------------- |211| **Setup Complexity** | Setup once, reuse | Manual creation needed for each test |212| **Maintainability** | Dependency changes only in one place | Need to modify all tests that use it |213| **Consistency** | Consistent with production code DI | May be inconsistent with actual application |214| **Test Readability** | Focus on test logic | Interfered by dependency creation code |215| **Scope Management** | Automatic service scope management | Need to manually manage object lifecycle |216| **Error Risk** | Framework guarantees correct injection | May miss or incorrectly create dependencies |217218---219220## Execution Control and Test Quality221222- **`[Retry(n)]`**: Only for unstable tests caused by external dependencies (network, file locking), not for logic errors223- **`[Timeout(ms)]`**: Set reasonable upper limit for performance-sensitive tests, validate SLA with `Stopwatch`224- **`[DisplayName]`**: Supports `{0}` parameter interpolation, making test reports more business-language aligned225226> Full examples (Retry/Timeout/DisplayName) please refer to [references/execution-control.md](references/execution-control.md)227228---229230## ASP.NET Core Integration Testing231232Using `WebApplicationFactory<Program>` in TUnit for ASP.NET Core integration testing, managing lifecycle through `IDisposable` implementation. Covers API response validation, Content-Type header checking, and performance baseline and parallel load testing.233234> Full WebApplicationFactory integration and load testing examples please refer to [references/aspnet-integration.md](references/aspnet-integration.md)235236---237238## TUnit + Testcontainers Infrastructure Orchestration239240Using `[Before(Assembly)]` / `[After(Assembly)]` at Assembly level to manage multi-container orchestration for PostgreSQL, Redis, Kafka, combined with `NetworkBuilder` to create shared network. Containers only start once, significantly reducing startup time and resource consumption while maintaining data isolation between tests.241242> Full multi-container orchestration and global sharing examples please refer to [references/tunit-testcontainers.md](references/tunit-testcontainers.md)243244---245246## TUnit Engine Modes247248### Source Generation Mode (Default Mode)249250```text251████████╗██╗ ██╗███╗ ██╗██╗████████╗252╚══██╔══╝██║ ██║████╗ ██║██║╚══██╔══╝253 ██║ ██║ ██║██╔██╗ ██║██║ ██║254 ██║ ██║ ██║██║╚██╗██║██║ ██║255 ██║ ╚██████╔╝██║ ╚████║██║ ██║256 ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝257258 Engine Mode: SourceGenerated259```text260261### Features and Advantages262263- **Compile-time generation**: All test discovery logic generated at compile time, no runtime reflection needed264- **Excellent performance**: Several times faster than reflection mode265- **Type safety**: Compile-time validation of test configuration and data sources266- **AOT compatible**: Fully supports Native AOT compilation267268### Reflection Mode269270```bash271# Enable reflection mode272dotnet run -- --reflection273274# Or set environment variable275$env:TUNIT_EXECUTION_MODE = "reflection"276dotnet run277```text278279### Applicable Scenarios280281- Dynamic test discovery282- F# and VB.NET projects (automatically used)283- Certain reflection-dependent test patterns284285### Native AOT Support286287```xml288<PropertyGroup>289 <PublishAot>true</PublishAot>290</PropertyGroup>291```text292293```bash294dotnet publish -c Release295```text296297---298299## Common Issues and Troubleshooting300301### Test Statistics Display Abnormal Issue302303**Problem:** `Test Summary: Total: 0, Failed: 0, Success: 0`304305### Solution Steps3063071. **Ensure project file is correctly configured:**308309```xml310<PropertyGroup>311 <IsTestProject>true</IsTestProject>312</PropertyGroup>313```text3143152. **Ensure GlobalUsings.cs is correct:**316317```csharp318global using System;319global using System.Collections.Generic;320global using System.Linq;321global using System.Threading.Tasks;322global using TUnit.Core;323global using TUnit.Assertions;324global using TUnit.Assertions.Extensions;325```text3263273. **Special configuration for integration tests:**328329```csharp330// Add at the end of WebApi project's Program.cs331public partial class Program { } // Allow integration tests to access332```text3333344. **Clean and rebuild:**335336```bash337dotnet clean; dotnet build338dotnet test --verbosity normal339```text340341### Source Generator Related Issues342343### Issue: Test classes not discoverable344345- **Solution**: Ensure project is fully rebuilt (`dotnet clean; dotnet build`)346347### Issue: Strange errors at compile time348349- **Solution**: Check if other Source Generator packages exist, consider updating to compatible versions350351### Diagnostic Options352353```ini354# .editorconfig355tunit.enable_verbose_diagnostics = true356```text357358```xml359<PropertyGroup>360 <TUnitEnableVerboseDiagnostics>true</TUnitEnableVerboseDiagnostics>361</PropertyGroup>362```text363364---365366## Practical Recommendations367368### Data-Driven Testing Selection Strategy369370- **MethodDataSource**: Suitable for dynamic data, complex objects, external file loading371- **ClassDataSource**: Suitable for shared data, AutoFixture integration, cross-test class reuse372- **Matrix Tests**: Suitable for combination testing, but control parameter quantity to avoid explosive growth373374### Execution Control Best Practices375376- **Retry**: Only for truly unstable external dependency tests377- **Timeout**: Set reasonable limits for performance-sensitive tests378- **DisplayName**: Make test reports more business-language aligned379380### Integration Testing Strategy381382- Use WebApplicationFactory for complete Web API testing383- Use TUnit + Testcontainers to build complex multi-service test environments384- Manage complex dependency relationships through attribute injection system385- Only test actually existing functionality, avoid testing non-existent endpoints386387---388389## Template Files390391| File Name | Description |392| --------- | ----------- |393| [data-source-examples.cs](templates/data-source-examples.cs) | MethodDataSource, ClassDataSource examples |394| [matrix-tests-examples.cs](templates/matrix-tests-examples.cs) | Matrix Tests combination testing examples |395| [lifecycle-di-examples.cs](templates/lifecycle-di-examples.cs) | Lifecycle management and dependency injection examples |396| [execution-control-examples.cs](templates/execution-control-examples.cs) | Retry, Timeout, DisplayName examples |397| [aspnet-integration-tests.cs](templates/aspnet-integration-tests.cs) | ASP.NET Core integration testing examples |398| [testcontainers-examples.cs](templates/testcontainers-examples.cs) | Testcontainers infrastructure orchestration examples |399400---401402## Reference Resources403404### Original Articles405406This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:407408- **Day 29 - TUnit Advanced Applications: Data-Driven Testing and Dependency Injection Deep Practice**409 - Article: https://ithelp.ithome.com.tw/articles/10377970410 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day29411412- **Day 30 - TUnit Advanced Applications - Execution Control and Test Quality and ASP.NET Core Integration Testing**413 - Article: https://ithelp.ithome.com.tw/articles/10378176414 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day30415416### TUnit Official Resources417418- [TUnit Official Website](https://tunit.dev/)419- [TUnit GitHub Repository](https://github.com/thomhurst/TUnit)420421### Advanced Feature Documentation422423- [TUnit Method Data Source Documentation](https://tunit.dev/docs/test-authoring/method-data-source)424- [TUnit Class Data Source Documentation](https://tunit.dev/docs/test-authoring/class-data-source)425- [TUnit Matrix Tests Documentation](https://tunit.dev/docs/test-authoring/matrix-tests)426- [TUnit Properties Documentation](https://tunit.dev/docs/test-lifecycle/properties)427- [TUnit Dependency Injection Documentation](https://tunit.dev/docs/test-lifecycle/dependency-injection)428- [TUnit Retrying Documentation](https://tunit.dev/docs/execution/retrying)429- [TUnit Timeouts Documentation](https://tunit.dev/docs/execution/timeouts)430- [TUnit Engine Modes Documentation](https://tunit.dev/docs/execution/engine-modes)431- [TUnit ASP.NET Core Documentation](https://tunit.dev/docs/examples/aspnet)432- [TUnit Complex Test Infrastructure](https://tunit.dev/docs/examples/complex-test-infrastructure-orchestration)433434### Testcontainers Related Resources435436- [Testcontainers.NET Official Website](https://dotnet.testcontainers.org/)437- [Testcontainers.NET GitHub](https://github.com/testcontainers/testcontainers-dotnet)438````