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-43category: testing4subcategory: frameworks5description: |6 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.7 Keywords: TUnit advanced, TUnit advanced, MethodDataSource, ClassDataSource, Matrix Tests, MatrixDataSource, MicrosoftDependencyInjectionDataSource, Property, Retry, Timeout, data-driven testing, test filtering, WebApplicationFactory TUnit, multi-container orchestration8targets: ['*']9license: MIT10metadata:11 source: https://skillmd.com/skills/rudironsoni/dotnet-testing-advanced-tunit-advanced-412 author: Kevin Tseng13 version: '1.0.0'14 tags: 'tunit, advanced-testing, data-driven, dependency-injection, integration-testing, testcontainers'15 related_skills: 'advanced-tunit-fundamentals, advanced-webapi-integration-testing'16claudecode: {}17opencode: {}18codexcli:19 short-description: '.NET skill guidance for dotnet-testing-advanced-tunit-advanced'20copilot: {}21geminicli: {}22antigravity: {}23---2425Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.2627# TUnit Advanced Applications: Data-Driven Testing, Dependency Injection, and Integration Testing2829## Applicable Scenarios3031This skill covers TUnit advanced application techniques, from data-driven testing to dependency injection, from32execution control to ASP.NET Core integration testing practice.3334### Core Topics3536- Data-driven testing advanced techniques (MethodDataSource, ClassDataSource, Matrix Tests)37- Properties attribute marking and test filtering38- Test lifecycle and dependency injection39- Execution control (Retry, Timeout, DisplayName)40- ASP.NET Core integration testing (WebApplicationFactory)41- Performance testing and load testing42- TUnit + Testcontainers complex infrastructure orchestration43- TUnit Engine Modes and troubleshooting4445---4647## Data-Driven Testing Advanced Techniques4849TUnit provides MethodDataSource, ClassDataSource, and Matrix Tests as three advanced data sources. MethodDataSource is50most flexible, supporting dynamic generation and external file loading; ClassDataSource is suitable for cross-test class51data sharing and AutoFixture integration; Matrix Tests automatically generates all parameter combinations (note: control52quantity to avoid explosive growth).5354> Full examples and comparison table please refer to55> [references/data-driven-testing.md](references/data-driven-testing.md)5657---5859## Properties Attribute Marking and Test Filtering6061### Basic Properties Usage6263````csharp64[Test]65[Property("Category", "Database")]66[Property("Priority", "High")]67public async Task DatabaseTest_HighPriority_ShouldBeFilterableByAttribute()68{69 await Assert.That(true).IsTrue();70}7172[Test]73[Property("Category", "Unit")]74[Property("Priority", "Medium")]75public async Task UnitTest_MediumPriority_BasicValidation()76{77 await Assert.That(1 + 1).IsEqualTo(2);78}7980[Test]81[Property("Category", "Integration")]82[Property("Priority", "Low")]83[Property("Environment", "Development")]84public async Task IntegrationTest_LowPriority_OnlyRunInDevEnvironment()85{86 await Assert.That("Hello World").Contains("World");87}88```text8990### Establishing Consistent Attribute Naming Conventions9192```csharp93public static class TestProperties94{95 // Test categories96 public const string CATEGORY_UNIT = "Unit";97 public const string CATEGORY_INTEGRATION = "Integration";98 public const string CATEGORY_E2E = "E2E";99100 // Priority levels101 public const string PRIORITY_CRITICAL = "Critical";102 public const string PRIORITY_HIGH = "High";103 public const string PRIORITY_MEDIUM = "Medium";104 public const string PRIORITY_LOW = "Low";105106 // Environments107 public const string ENV_DEVELOPMENT = "Development";108 public const string ENV_STAGING = "Staging";109 public const string ENV_PRODUCTION = "Production";110}111112[Test]113[Property("Category", TestProperties.CATEGORY_UNIT)]114[Property("Priority", TestProperties.PRIORITY_HIGH)]115public async Task ExampleTest_UsingConstants_EnsuresConsistency()116{117 await Assert.That(1 + 1).IsEqualTo(2);118}119```text120121### TUnit Test Filtering Execution122123TUnit uses `dotnet run` instead of `dotnet test`:124125```bash126# Only run unit tests127dotnet run --treenode-filter "/*/*/*/*[Category=Unit]"128129# Only run high priority tests130dotnet run --treenode-filter "/*/*/*/*[Priority=High]"131132# Combined conditions: run high priority unit tests133dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)&(Priority=High)]"134135# OR condition: run unit tests or smoke tests136dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)|(Suite=Smoke)]"137138# Run tests for specific features139dotnet run --treenode-filter "/*/*/*/*[Feature=OrderProcessing]"140```text141142### Filter Syntax Notes143144- Path pattern `/*/*/*/*` represents Assembly/Namespace/Class/Method level145- Attribute names are case-sensitive146- Combined conditions must be properly enclosed in parentheses147148---149150## Test Lifecycle Management151152TUnit 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.153154> Full attribute family and examples please refer to [references/lifecycle-management.md](references/lifecycle-management.md)155156---157158## Dependency Injection Patterns159160### TUnit Dependency Injection Core Concepts161162TUnit's dependency injection is built on Data Source Generators:163164```csharp165public class MicrosoftDependencyInjectionDataSourceAttribute : DependencyInjectionDataSourceAttribute<IServiceScope>166{167 private static readonly IServiceProvider ServiceProvider = CreateSharedServiceProvider();168169 public override IServiceScope CreateScope(DataGeneratorMetadata dataGeneratorMetadata)170 {171 return ServiceProvider.CreateScope();172 }173174 public override object? Create(IServiceScope scope, Type type)175 {176 return scope.ServiceProvider.GetService(type);177 }178179 private static IServiceProvider CreateSharedServiceProvider()180 {181 return new ServiceCollection()182 .AddSingleton<IOrderRepository, MockOrderRepository>()183 .AddSingleton<IDiscountCalculator, MockDiscountCalculator>()184 .AddSingleton<IShippingCalculator, MockShippingCalculator>()185 .AddSingleton<ILogger<OrderService>, MockLogger<OrderService>>()186 .AddTransient<OrderService>()187 .BuildServiceProvider();188 }189}190```text191192### Using TUnit Dependency Injection193194```csharp195[MicrosoftDependencyInjectionDataSource]196public class DependencyInjectionTests(OrderService orderService)197{198 [Test]199 public async Task CreateOrder_UsingTUnitDependencyInjection_ShouldWorkCorrectly()200 {201 // Arrange - dependencies automatically injected through TUnit DI202 var items = new List<OrderItem>203 {204 new() { ProductId = "PROD001", ProductName = "Test Product", UnitPrice = 100m, Quantity = 2 }205 };206207 // Act208 var order = await orderService.CreateOrderAsync("CUST001", CustomerLevel.VIP, items);209210 // Assert211 await Assert.That(order).IsNotNull();212 await Assert.That(order.CustomerId).IsEqualTo("CUST001");213 await Assert.That(order.CustomerLevel).IsEqualTo(CustomerLevel.VIP);214 }215216 [Test]217 public async Task TUnitDependencyInjection_ValidateAutoInjection_ServiceShouldBeCorrectType()218 {219 await Assert.That(orderService).IsNotNull();220 await Assert.That(orderService.GetType().Name).IsEqualTo("OrderService");221 }222}223```text224225### TUnit DI vs Manual Dependency Creation Comparison226227| Feature | TUnit DI | Manual Dependency Creation |228| :------ | :------- | :------------------------- |229| **Setup Complexity** | Setup once, reuse | Manual creation needed for each test |230| **Maintainability** | Dependency changes only in one place | Need to modify all tests that use it |231| **Consistency** | Consistent with production code DI | May be inconsistent with actual application |232| **Test Readability** | Focus on test logic | Interfered by dependency creation code |233| **Scope Management** | Automatic service scope management | Need to manually manage object lifecycle |234| **Error Risk** | Framework guarantees correct injection | May miss or incorrectly create dependencies |235236---237238## Execution Control and Test Quality239240- **`[Retry(n)]`**: Only for unstable tests caused by external dependencies (network, file locking), not for logic errors241- **`[Timeout(ms)]`**: Set reasonable upper limit for performance-sensitive tests, validate SLA with `Stopwatch`242- **`[DisplayName]`**: Supports `{0}` parameter interpolation, making test reports more business-language aligned243244> Full examples (Retry/Timeout/DisplayName) please refer to [references/execution-control.md](references/execution-control.md)245246---247248## ASP.NET Core Integration Testing249250Using `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.251252> Full WebApplicationFactory integration and load testing examples please refer to [references/aspnet-integration.md](references/aspnet-integration.md)253254---255256## TUnit + Testcontainers Infrastructure Orchestration257258Using `[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.259260> Full multi-container orchestration and global sharing examples please refer to [references/tunit-testcontainers.md](references/tunit-testcontainers.md)261262---263264## TUnit Engine Modes265266### Source Generation Mode (Default Mode)267268```text269████████╗██╗ ██╗███╗ ██╗██╗████████╗270╚══██╔══╝██║ ██║████╗ ██║██║╚══██╔══╝271 ██║ ██║ ██║██╔██╗ ██║██║ ██║272 ██║ ██║ ██║██║╚██╗██║██║ ██║273 ██║ ╚██████╔╝██║ ╚████║██║ ██║274 ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝275276 Engine Mode: SourceGenerated277```text278279### Features and Advantages280281- **Compile-time generation**: All test discovery logic generated at compile time, no runtime reflection needed282- **Excellent performance**: Several times faster than reflection mode283- **Type safety**: Compile-time validation of test configuration and data sources284- **AOT compatible**: Fully supports Native AOT compilation285286### Reflection Mode287288```bash289# Enable reflection mode290dotnet run -- --reflection291292# Or set environment variable293$env:TUNIT_EXECUTION_MODE = "reflection"294dotnet run295```text296297### Applicable Scenarios298299- Dynamic test discovery300- F# and VB.NET projects (automatically used)301- Certain reflection-dependent test patterns302303### Native AOT Support304305```xml306<PropertyGroup>307 <PublishAot>true</PublishAot>308</PropertyGroup>309```text310311```bash312dotnet publish -c Release313```text314315---316317## Common Issues and Troubleshooting318319### Test Statistics Display Abnormal Issue320321**Problem:** `Test Summary: Total: 0, Failed: 0, Success: 0`322323### Solution Steps3243251. **Ensure project file is correctly configured:**326327```xml328<PropertyGroup>329 <IsTestProject>true</IsTestProject>330</PropertyGroup>331```text3323332. **Ensure GlobalUsings.cs is correct:**334335```csharp336global using System;337global using System.Collections.Generic;338global using System.Linq;339global using System.Threading.Tasks;340global using TUnit.Core;341global using TUnit.Assertions;342global using TUnit.Assertions.Extensions;343```text3443453. **Special configuration for integration tests:**346347```csharp348// Add at the end of WebApi project's Program.cs349public partial class Program { } // Allow integration tests to access350```text3513524. **Clean and rebuild:**353354```bash355dotnet clean; dotnet build356dotnet test --verbosity normal357```text358359### Source Generator Related Issues360361### Issue: Test classes not discoverable362363- **Solution**: Ensure project is fully rebuilt (`dotnet clean; dotnet build`)364365### Issue: Strange errors at compile time366367- **Solution**: Check if other Source Generator packages exist, consider updating to compatible versions368369### Diagnostic Options370371```ini372# .editorconfig373tunit.enable_verbose_diagnostics = true374```text375376```xml377<PropertyGroup>378 <TUnitEnableVerboseDiagnostics>true</TUnitEnableVerboseDiagnostics>379</PropertyGroup>380```text381382---383384## Practical Recommendations385386### Data-Driven Testing Selection Strategy387388- **MethodDataSource**: Suitable for dynamic data, complex objects, external file loading389- **ClassDataSource**: Suitable for shared data, AutoFixture integration, cross-test class reuse390- **Matrix Tests**: Suitable for combination testing, but control parameter quantity to avoid explosive growth391392### Execution Control Best Practices393394- **Retry**: Only for truly unstable external dependency tests395- **Timeout**: Set reasonable limits for performance-sensitive tests396- **DisplayName**: Make test reports more business-language aligned397398### Integration Testing Strategy399400- Use WebApplicationFactory for complete Web API testing401- Use TUnit + Testcontainers to build complex multi-service test environments402- Manage complex dependency relationships through attribute injection system403- Only test actually existing functionality, avoid testing non-existent endpoints404405---406407## Template Files408409| File Name | Description |410| --------- | ----------- |411| [data-source-examples.cs](templates/data-source-examples.cs) | MethodDataSource, ClassDataSource examples |412| [matrix-tests-examples.cs](templates/matrix-tests-examples.cs) | Matrix Tests combination testing examples |413| [lifecycle-di-examples.cs](templates/lifecycle-di-examples.cs) | Lifecycle management and dependency injection examples |414| [execution-control-examples.cs](templates/execution-control-examples.cs) | Retry, Timeout, DisplayName examples |415| [aspnet-integration-tests.cs](templates/aspnet-integration-tests.cs) | ASP.NET Core integration testing examples |416| [testcontainers-examples.cs](templates/testcontainers-examples.cs) | Testcontainers infrastructure orchestration examples |417418---419420## Reference Resources421422### Original Articles423424This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:425426- **Day 29 - TUnit Advanced Applications: Data-Driven Testing and Dependency Injection Deep Practice**427 - Article: https://ithelp.ithome.com.tw/articles/10377970428 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day29429430- **Day 30 - TUnit Advanced Applications - Execution Control and Test Quality and ASP.NET Core Integration Testing**431 - Article: https://ithelp.ithome.com.tw/articles/10378176432 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day30433434### TUnit Official Resources435436- [TUnit Official Website](https://tunit.dev/)437- [TUnit GitHub Repository](https://github.com/thomhurst/TUnit)438439### Advanced Feature Documentation440441- [TUnit Method Data Source Documentation](https://tunit.dev/docs/test-authoring/method-data-source)442- [TUnit Class Data Source Documentation](https://tunit.dev/docs/test-authoring/class-data-source)443- [TUnit Matrix Tests Documentation](https://tunit.dev/docs/test-authoring/matrix-tests)444- [TUnit Properties Documentation](https://tunit.dev/docs/test-lifecycle/properties)445- [TUnit Dependency Injection Documentation](https://tunit.dev/docs/test-lifecycle/dependency-injection)446- [TUnit Retrying Documentation](https://tunit.dev/docs/execution/retrying)447- [TUnit Timeouts Documentation](https://tunit.dev/docs/execution/timeouts)448- [TUnit Engine Modes Documentation](https://tunit.dev/docs/execution/engine-modes)449- [TUnit ASP.NET Core Documentation](https://tunit.dev/docs/examples/aspnet)450- [TUnit Complex Test Infrastructure](https://tunit.dev/docs/examples/complex-test-infrastructure-orchestration)451452### Testcontainers Related Resources453454- [Testcontainers.NET Official Website](https://dotnet.testcontainers.org/)455- [Testcontainers.NET GitHub](https://github.com/testcontainers/testcontainers-dotnet)456````