Aller au contenu
Skillpedia
Tests5.8k · #14642

testability-obstacle

Ce qu’il fait

Cette compétence ajoute le plus petit changement nécessaire pour rendre testable un comportement C#, comme le contrôle de l'heure actuelle ou l'évitement des accès réels aux fichiers. Elle s'adresse aux développeurs qui ont besoin de tests déterministes pour du code qui dépend de fonctionnalités du système.

Quand l’utiliser

  • ✓Quand un test lirait ou écrirait autrement sur le vrai système de fichiers.
  • ✓Quand un comportement dépend de l'heure actuelle, d'un délai, d'une valeur aléatoire ou de l'environnement et doit être contrôlé.
  • ✓Quand les tests existants ne peuvent pas contrôler une dépendance sans modifier les paramètres globaux du processus.

Lien du skill

https://github.com/dotnet/skills/blob/main/plugins/dotnet-test/skills/testability-obstacle/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/dotnet/skills/blob/main/plugins/dotnet-test/skills/testability-obstacle/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Mon test du générateur de rapports écrit sur le disque réel et dépend de DateTime.Now. Ajoute le plus petit point d'accès pour que je puisse le tester de façon déterministe.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

L'agent ajoute un point d'injection étroit qui laisse fonctionner les appels d'origine, puis écrit des tests déterministes qui utilisent un faux objet pour cette dépendance.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis GitHub.

Resolve a Testability Obstacle

Introduce the smallest behavior-preserving seam needed to test a specific C# behavior, then add deterministic tests that prove both the behavior and the seam. The production edit is a means to the requested test, not an invitation to redesign adjacent code.

When to Use

  • A requested test would otherwise read/write the real filesystem.
  • Behavior depends on the current time, delay, random value, environment, console, process, or another ambient dependency.
  • The user explicitly permits or requests a safe production seam.
  • Existing tests cannot control a dependency without process-global mutation.

When Not to Use

  • The dependency is already injected or passed as an argument. Write tests with a fake through the existing seam using code-testing.
  • The user wants a repository-wide testability audit. Use detect-static-dependencies.
  • The user wants wrappers generated but not call sites/tests changed. Use generate-testability-wrappers.
  • The user requests a broad mechanical migration. Use migrate-static-to-wrapper, then generate tests separately.
  • The user already selected an existing replacement such as TimeProvider or IFileSystem and asks to migrate call sites to it. Use migrate-static-to-wrapper, which also updates affected tests.
  • The code is not C#/.NET.

Inputs

Input Required Description
Behavior to test Yes The method/workflow and expected observable behavior
Target scope No Discover the narrowest relevant file/project when omitted
Allowed production changes No Default to the minimum internal/constructor seam

Workflow

Step 1: Prove the obstacle

Read the target production path and its existing tests. Identify the exact ambient operation preventing a deterministic test and the behavior that must remain unchanged. Do not run a repository-wide static scan for a single-class request.

If an adequate seam already exists, stop refactoring and use it. This skill adds no value when a fake can already be supplied.

Step 2: Select the smallest safe seam

Choose by dependency and repository constraints:

Dependency Preferred seam
Current time / timers Inject TimeProvider; use FakeTimeProvider in tests
Filesystem Existing repository abstraction; for one write/read operation use an injected delegate when conventions allow, otherwise a one-member interface or an already accepted System.IO.Abstractions
HTTP Existing typed HttpClient/handler or IHttpClientFactory seam
Randomness One final generated value: inject Func<int> and keep range selection in the real default; inject Func<int, int, int> only when range arguments are behavior the test must verify; multiple operations/state: inject Random or a minimal generator interface
Environment/console/process Minimal interface containing only members used by the target

The scoped AsyncLocal<T> rule applies to every static API that must retain its public static shape — clocks, filesystem access, environment lookups, identity generation, and randomness. The scope captures and restores the previous value; never implement Dispose() as an unconditional assignment to null. Store the provider/value itself in AsyncLocal<T>. Do not put a mutable Stack<T>, list, or other shared mutable collection in the slot: child execution contexts can inherit the same object and corrupt each other's nesting. When the provider itself is mutable (for example an in-memory store or fake time provider), establish a fresh provider inside each parallel flow rather than mutating one inherited instance from a parent context.

Constructor injection is the default for instance classes. Reuse the repository's DI and naming conventions, but do not add a DI container to a class library just to satisfy this workflow.

Preserve the existing public construction surface unless the user authorizes an API change. Keep a public parameterless constructor as the real-dependency default and place a test-only delegate/provider constructor at the narrowest visibility the test project can reach. Do not turn the seam into a new public optional parameter merely for test convenience.

For a static class or a public API that cannot change, use a scoped ambient seam only when constructor/parameter injection is impossible. The override must:

  • flow across await (AsyncLocal<T>, not `[ThreadS
Questions fréquentes

Va-t-elle restructurer mon code ?

Non. La modification de production se limite à ce que le test demandé exige.

Que faire si la dépendance est déjà injectée ?

Dans ce cas, aucun point d'accès n'est nécessaire, et la compétence vous oriente vers l'écriture de tests avec un faux objet via le point d'accès existant.

Migre-t-elle tout le projet ?

Non. Les migrations de grande ampleur relèvent d'une compétence distincte.

Détails

Description originale de l’auteur

MUST USE for C#/.NET deterministic tests that require the smallest production seam for DateTime/Task.Delay/File/Environment/Guid/Random, static API preservation, nested/parallel overrides, or no real I/O. USE ONLY when the target workspace contains C# source plus a .csproj or .sln. DO NOT USE for audits, bulk migration, code that already has an injectable seam, or an explicit migration to a user-named existing abstraction (migrate-static-to-wrapper). Use instead of general test generation when the requested test is impossible without a production edit and seam selection is still open.

repo: dotnet/skills

Popularité

Étoiles GitHub
5.8k
Position au classement
#14642
Licence
MIT
Mis à jour
02/11/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires