Skip to main content
dotnet-testing-autodata-xunit-integration AutoFixture 與 xUnit 整合完整指南。當需要使用 AutoData 或 InlineAutoData 簡化 xUnit 參數化測試資料準備時使用。涵蓋自訂 Customization 與測試資料屬性,提升測試可讀性與維護性。
Make sure to use this skill whenever the user mentions AutoData, InlineAutoData, MemberAutoData, AutoFixture xUnit integration, or parameterized test data attributes, even if they don't explicitly ask for AutoData guidance.
Keywords: AutoData, InlineAutoData, AutoFixture xUnit, [AutoData], [InlineAutoData], AutoDataAttribute, ICustomization, DataAttribute, 參數化測試, Theory AutoData, MemberAutoData, 測試資料屬性, fixture.Customize
Jump to install Skills Marketplace Discover and explore AI skills built by the community.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Copy promptShow prompt details A direct command skips the review prompt. Inspect the source before running it.
npx skills add https://github.com/kevintsengtw/dotnet-testing-agent-skills --skill dotnet-testing-autodata-xunit-integrationThe command stays on one line. Scroll horizontally to inspect it before copying.
Prefer a local copy? Download the files currently available to SkillsMP.
Download Zip Downloading... Related occupations SOC
Based on SOC occupation classification
More from this repository
name dotnet-testing-autodata-xunit-integration description AutoFixture 與 xUnit 整合完整指南。當需要使用 AutoData 或 InlineAutoData 簡化 xUnit 參數化測試資料準備時使用。涵蓋自訂 Customization 與測試資料屬性,提升測試可讀性與維護性。
Make sure to use this skill whenever the user mentions AutoData, InlineAutoData, MemberAutoData, AutoFixture xUnit integration, or parameterized test data attributes, even if they don't explicitly ask for AutoData guidance.
Keywords: AutoData, InlineAutoData, AutoFixture xUnit, [AutoData], [InlineAutoData], AutoDataAttribute, ICustomization, DataAttribute, 參數化測試, Theory AutoData, MemberAutoData, 測試資料屬性, fixture.Customize
AutoData 屬性家族:xUnit 與 AutoFixture 的整合應用
概述
AutoData 屬性家族是 AutoFixture.Xunit2 套件提供的功能,將 AutoFixture 的資料產生能力與 xUnit 的參數化測試整合,讓測試參數自動注入,大幅減少測試準備程式碼。
核心特色
AutoData :自動產生所有測試參數
InlineAutoData :混合固定值與自動產生
MemberAutoData :結合外部資料來源
CompositeAutoData :多重資料來源整合
CollectionSizeAttribute :控制集合產生數量
安裝套件
<PackageReference Include ="AutoFixture" Version ="4.18.1" />
<PackageReference Include ="AutoFixture.Xunit2" Version ="4.18.1" />
dotnet add package AutoFixture.Xunit2
AutoData:完全自動產生參數
AutoData 是最基礎的屬性,自動為測試方法的所有參數產生測試資料。
基本使用
AutoFixture.Xunit2;
{
Guid Id { ; ; }
[ ]
Name { ; ; } = .Empty;
[ ]
Age { ; ; }
Email { ; ; } = .Empty;
DateTime CreateTime { ; ; }
}
[ ]
[ ]
AutoData_應能自動產生所有參數(Person person, message, count)
{
person.Should().NotBeNull();
person.Id.Should().NotBe(Guid.Empty);
person.Name.Should().HaveLength( );
person.Age.Should().BeInRange( , );
message.Should().NotBeNullOrEmpty();
count.Should().NotBe( );
}
using
public
class
Person
public
get
set
StringLength(10)
public
string
get
set
string
Range(18, 80)
public
int
get
set
public
string
get
set
string
public
get
set
Theory
AutoData
public
void
string
int
10
18
80
0
透過 DataAnnotation 約束參數 [Theory ]
[AutoData ]
public void AutoData_透過DataAnnotation約束參數(
[StringLength(5, MinimumLength = 3) ] string shortName,
[Range(1, 100) ] int percentage,
Person person)
{
shortName.Length.Should().BeInRange(3 , 5 );
percentage.Should().BeInRange(1 , 100 );
person.Should().NotBeNull();
}
InlineAutoData:混合固定值與自動產生 InlineAutoData 結合了 InlineData 的固定值特性與 AutoData 的自動產生功能。
基本語法 [Theory ]
[InlineAutoData("VIP客戶" , 1000) ]
[InlineAutoData("一般客戶" , 500) ]
[InlineAutoData("新客戶" , 100) ]
public void InlineAutoData_混合固定值與自動產生(
string customerType,
decimal creditLimit,
Person person)
{
var customer = new Customer
{
Person = person,
Type = customerType,
CreditLimit = creditLimit
};
customer.Type.Should().Be(customerType);
customer.CreditLimit.Should().BeOneOf(1000 , 500 , 100 );
customer.Person.Should().NotBeNull();
}
參數順序一致性 [Theory ]
[InlineAutoData("產品A" , 100) ]
[InlineAutoData("產品B" , 200) ]
public void InlineAutoData_參數順序一致性(
string name,
decimal price,
string description,
Product product)
{
name.Should().BeOneOf("產品A" , "產品B" );
price.Should().BeOneOf(100 , 200 );
description.Should().NotBeNullOrEmpty();
product.Should().NotBeNull();
}
重要限制:只能使用編譯時常數
[InlineAutoData("VIP" , 100000) ]
[InlineAutoData("Premium" , 50000) ]
private const decimal VipCreditLimit = 100000 m;
[InlineAutoData("VIP" , VipCreditLimit) ]
[InlineAutoData("VIP" , 100 * 1000) ]
需要使用複雜資料時,應使用 MemberAutoData。
MemberAutoData:結合外部資料來源 MemberAutoData 允許從類別的方法、屬性或欄位中獲取測試資料。
使用靜態方法 public class MemberAutoDataTests
{
public static IEnumerable<object []> GetProductCategories()
{
yield return new object [] { "3C產品" , "TECH" };
yield return new object [] { "服飾配件" , "FASHION" };
yield return new object [] { "居家生活" , "HOME" };
yield return new object [] { "運動健身" , "SPORTS" };
}
[Theory ]
[MemberAutoData(nameof(GetProductCategories)) ]
public void MemberAutoData_使用靜態方法資料(
string categoryName,
string categoryCode,
Product product)
{
var categorizedProduct = new CategorizedProduct
{
Product = product,
CategoryName = categoryName,
CategoryCode = categoryCode
};
categorizedProduct.CategoryName.Should().Be(categoryName);
categorizedProduct.CategoryCode.Should().Be(categoryCode);
categorizedProduct.Product.Should().NotBeNull();
}
}
使用靜態屬性 public static IEnumerable<object []> StatusTransitions => new []
{
new object [] { OrderStatus.Created, OrderStatus.Confirmed },
new object [] { OrderStatus.Confirmed, OrderStatus.Shipped },
new object [] { OrderStatus.Shipped, OrderStatus.Delivered },
new object [] { OrderStatus.Delivered, OrderStatus.Completed }
};
[Theory ]
[MemberAutoData(nameof(StatusTransitions)) ]
public void MemberAutoData_使用靜態屬性_訂單狀態轉換(
OrderStatus fromStatus,
OrderStatus toStatus,
Order order)
{
order.Status = fromStatus;
order.TransitionTo(toStatus);
order.Status.Should().Be(toStatus);
}
自訂 AutoData 屬性
DomainAutoDataAttribute public class DomainAutoDataAttribute : AutoDataAttribute
{
public DomainAutoDataAttribute () : base (( ) => CreateFixture())
{
}
private static IFixture CreateFixture ()
{
var fixture = new Fixture();
fixture.Customize<Person>(composer => composer
.With(p => p.Age, () => Random.Shared.Next(18 , 65 ))
.With(p => p.Email, () => $"user{Random.Shared.Next(1000 )} @example.com" )
.With(p => p.Name, () => $"測試用戶{Random.Shared.Next(100 )} " ));
fixture.Customize<Product>(composer => composer
.With(p => p.Price, () => Random.Shared.Next(100 , 10000 ))
.With(p => p.IsAvailable, true )
.With(p => p.Name, () => $"產品{Random.Shared.Next(1000 )} " ));
return fixture;
}
}
BusinessAutoDataAttribute public class BusinessAutoDataAttribute : AutoDataAttribute
{
public BusinessAutoDataAttribute () : base (( ) => CreateFixture())
{
}
private static IFixture CreateFixture ()
{
var fixture = new Fixture();
fixture.Customize<Order>(composer => composer
.With(o => o.Status, OrderStatus.Created)
.With(o => o.Amount, () => Random.Shared.Next(1000 , 50000 ))
.With(o => o.OrderNumber, () => $"ORD{DateTime.Now:yyyyMMdd} {Random.Shared.Next(1000 ):D4} " ));
return fixture;
}
}
使用自訂 AutoData [Theory ]
[DomainAutoData ]
public void 使用DomainAutoData(Person person, Product product)
{
person.Age.Should().BeInRange(18 , 64 );
person.Email.Should().EndWith("@example.com" );
product.IsAvailable.Should().BeTrue();
}
[Theory ]
[BusinessAutoData ]
public void 使用BusinessAutoData(Order order)
{
order.Status.Should().Be(OrderStatus.Created);
order.Amount.Should().BeInRange(1000 , 49999 );
order.OrderNumber.Should().StartWith("ORD" );
}
CompositeAutoData:多重資料來源整合 透過繼承 AutoDataAttribute 並以反射合併多個 Fixture 的 Customizations,組合多個自訂 AutoData 配置:
[Theory ]
[CompositeAutoData(typeof(DomainAutoDataAttribute), typeof(BusinessAutoDataAttribute)) ]
public void CompositeAutoData_整合多重資料來源(
Person person, Product product, Order order)
{
person.Age.Should().BeInRange(18 , 64 );
product.IsAvailable.Should().BeTrue();
order.Status.Should().Be(OrderStatus.Created);
}
CollectionSizeAttribute:控制集合大小
外部測試資料整合 整合 CSV、JSON 等外部資料來源與 MemberAutoData,同時保留 AutoFixture 自動產生其餘參數的能力。完整指南請參考 外部測試資料整合 。
資料來源設計模式 階層式資料組織與可重用資料集的設計模式,建立 BaseTestData 基底類別統一管理測試資料路徑。完整範例請參考 資料來源設計模式 。
與 Awesome Assertions 協作 [Theory ]
[InlineAutoData("VIP" , 100000) ]
[InlineAutoData("Premium" , 50000) ]
[InlineAutoData("Regular" , 20000) ]
public void AutoData與AwesomeAssertions協作_客戶等級驗證(
string customerLevel,
decimal expectedCreditLimit,
[Range(1000, 15000) ] decimal orderAmount,
Customer customer,
Order order)
{
customer.Type = customerLevel;
customer.CreditLimit = expectedCreditLimit;
order.Amount = orderAmount;
var canPlaceOrder = customer.CanPlaceOrder(order.Amount);
var discountRate = CalculateDiscount(customer.Type, order.Amount);
customer.Type.Should().Be(customerLevel);
customer.CreditLimit.Should().Be(expectedCreditLimit);
customer.CreditLimit.Should().BePositive();
order.Amount.Should().BeInRange(1000 m, 15000 m);
canPlaceOrder.Should().BeTrue();
discountRate.Should().BeInRange(0 m, 0.3 m);
}
private static decimal CalculateDiscount (string customerType, decimal orderAmount )
{
var baseDiscount = customerType switch
{
"VIP" => 0.15 m,
"Premium" => 0.10 m,
"Regular" => 0.05 m,
_ => 0 m
};
var largeOrderBonus = orderAmount > 30000 m ? 0.05 m : 0 m;
return Math.Min(baseDiscount + largeOrderBonus, 0.3 m);
}
最佳實踐
應該做
善用 DataAnnotation
在參數上使用 [StringLength]、[Range] 約束資料範圍
確保產生的資料符合業務規則
建立可重用的自訂 AutoData
為不同領域建立專屬的 AutoData 屬性
集中管理測試資料的產生規則
使用 MemberAutoData 處理複雜資料
當 InlineAutoData 無法滿足需求時使用
支援變數、運算式和外部資料來源
組織測試資料來源
應該避免
在 InlineAutoData 使用非常數值
InlineAutoData 只接受編譯時常數
需要動態值時改用 MemberAutoData
過度複雜的 CompositeAutoData
避免組合過多的 AutoData 來源
保持配置的可理解性
忽略參數順序
InlineAutoData 的固定值必須與參數順序一致
錯誤的順序會導致型別不符
程式碼範本
與其他技能的關係
autofixture-basics :本技能的前置知識
autofixture-customization :自訂化策略可用於 AutoData 屬性
autofixture-nsubstitute-integration :下一步學習目標
awesome-assertions-guide :搭配使用提升測試可讀性
輸出格式
產生使用 [Theory] 搭配 [AutoData] 或 [InlineAutoData] 的測試方法
產生自訂 AutoDataAttribute 衍生類別檔案(*AutoDataAttribute.cs)
測試參數透過屬性注入,減少 Arrange 區段程式碼
固定值參數置於方法簽章前方,自動產生參數置於後方
搭配 DataAnnotation 約束參數範圍
參考資源
原始文章 本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
Day 12 - 結合 AutoData:xUnit 與 AutoFixture 的整合應用
官方文件 dotnet-testing-advanced-aspire-testing .NET Aspire Testing 整合測試框架完整指南。當需要測試 .NET Aspire 分散式應用程式、設定 AppHost 測試或從 Testcontainers 遷移至 Aspire 測試時使用。涵蓋 DistributedApplicationTestingBuilder、容器生命週期管理、多服務編排、Respawn 配置與時間可測試性設計。
Make sure to use this skill whenever the user mentions .NET Aspire, AppHost testing, DistributedApplicationTestingBuilder, cloud-native testing, or migrating from Testcontainers to Aspire, even if they don't explicitly ask for Aspire testing guidance.
Keywords: aspire testing, .NET Aspire, DistributedApplicationTestingBuilder, AppHost testing, 分散式測試, AspireAppFixture, IAsyncLifetime, ContainerLifetime.Session, 雲原生測試, 多服務整合, Aspire.Hosting.Testing, Respawn
dotnet-testing-advanced-aspnet-integration-testing ASP.NET Core 整合測試的專門技能。當需要測試 Web API 端點、HTTP 請求/回應、中介軟體、依賴注入時使用。涵蓋 WebApplicationFactory、TestServer、HttpClient 測試、記憶體資料庫配置等。
Make sure to use this skill whenever the user mentions ASP.NET Core integration testing, WebApplicationFactory, TestServer, HTTP endpoint testing, or middleware testing, even if they don't explicitly ask for integration testing guidance.
Keywords: integration testing, 整合測試, web api testing, WebApplicationFactory, TestServer, HttpClient testing, controller testing, endpoint testing, 端點測試, RESTful API testing, Microsoft.AspNetCore.Mvc.Testing, CreateClient, ConfigureWebHost, AwesomeAssertions.Web, Be200Ok, Be404NotFound, middleware testing, 中介軟體測試, dependency injection testing
.NET 進階測試技能總覽與引導中心。當使用者詢問「整合測試」、「API 測試」、「容器化測試」、「微服務測試」、「測試框架遷移」、「Testcontainers」、「Aspire 測試」等進階測試需求時觸發。會根據具體需求推薦適合的子技能組合,涵蓋整合測試、Testcontainers、Aspire 測試、框架升級等 8 個進階技能。
Make sure to use this skill whenever the user mentions integration testing, API testing, Testcontainers, .NET Aspire testing, WebApplicationFactory, or xUnit/TUnit migration, even if they don't explicitly ask for advanced testing guidance.
Keywords: integration testing, 整合測試, API testing, advanced testing, 進階測試, testcontainers, aspire testing, WebApplicationFactory, TestServer, database test, 資料庫測試, EF Core test, MongoDB test, Redis test, Docker test, 容器測試, microservice test, 微服務測試, .NET Aspire, xUnit upgrade, TUnit, framework migration