dotnet-testing-private-internal-testing — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited dotnet-testing-private-internal-testing (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
本技能協助您在 .NET 測試中正確處理私有與內部成員的測試,強調設計優先的測試思維。
回覆時必須完整涵蓋以下三種路徑,讓使用者根據實際情境選擇最適合的方式:
不要只推薦其中一種而忽略其他。即使首推重構,也必須說明 InternalsVisibleTo 和反射的做法與適用時機。
好的設計自然就有好的可測試性。如果你發現自己經常需要測試私有方法,很可能是設計出了問題。 但在實務上,並非所有情境都能立即重構,因此也需要了解 InternalsVisibleTo 和反射測試等替代方案。
將複雜私有邏輯提取為獨立類別(責任分離),或使用策略模式將計算邏輯注入為可測試的公開介面。包含 OrderProcessor 重構範例、PricingService 策略模式重構(重構前/後)、部分模擬範例。
完整重構範例與策略模式程式碼請參考 references/refactoring-patterns.md
適合的情境: 框架或類別庫開發、複雜的內部演算法驗證、效能關鍵的內部組件、安全相關的內部邏輯
不適合的情境: 應用層的業務邏輯(應該是 public)、簡單的輔助方法、可以透過公開 API 間接測試的邏輯
// 在主專案中的 AssemblyInfo.cs 或任何類別檔案中
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("YourProject.Tests")]
[assembly: InternalsVisibleTo("YourProject.IntegrationTests")]<!-- YourProject.csproj -->
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>$(AssemblyName).Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup><!-- YourProject.csproj -->
<ItemGroup>
<PackageReference Include="Meziantou.MSBuild.InternalsVisibleTo" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).Tests" />
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="002400000480000094..." />
</ItemGroup>參考資源:
| 評估面向 | 風險程度 | 說明 |
|---|---|---|
| 封裝性破壞 | 中等 | 增加了測試對內部實作的依賴 |
| 重構阻力 | 高 | 改變 internal 成員會影響測試 |
| 維護成本 | 中等 | 需要同步維護生產代碼和測試代碼 |
| 設計品質 | 低 | 如果過度使用,可能表示設計有問題 |
涵蓋決策樹(是否應測試私有方法)、反射測試私有實例方法與靜態方法、ReflectionTestHelper 輔助類別封裝,以及反射測試的風險與最佳實踐。
完整程式碼範例與技術細節請參考 references/private-method-testing.md
| 情境 | 建議做法 | 理由 |
|---|---|---|
| 簡單私有方法(< 10 行) | 透過公開方法測試 | 維護成本低 |
| 複雜私有邏輯(> 10 行) | 重構為獨立類別 | 改善設計與可測試性 |
| 框架內部演算法 | 使用 InternalsVisibleTo | 需要精確測試內部行為 |
| 遺留系統私有方法 | 考慮使用反射測試 | 短期內難以重構 |
| 安全相關私有邏輯 | 重構或使用反射測試 | 需要獨立驗證正確性 |
| 頻繁變動的實作細節 | 避免直接測試 | 測試會變得脆弱 |
回覆必須包含以下三個區塊(依優先順序排列,但全部都要提及):
本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
unit-test-fundamentals - 單元測試基礎nsubstitute-mocking - 測試替身與模擬~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.