testability-obstacle
O que ela faz
Esta skill faz a menor mudança necessária para tornar testável um comportamento de C#, como controlar a hora atual ou evitar acesso real a arquivos. É para desenvolvedores que precisam de testes determinísticos para um código que depende de recursos do sistema.
Quando usar
- ✓Quando um teste leria ou escreveria no sistema de arquivos real.
- ✓Quando o comportamento depende da hora atual, de um atraso, de um valor aleatório ou do ambiente e precisa ser controlado.
- ✓Quando os testes existentes não conseguem controlar uma dependência sem mudar configurações globais do processo.
Link da skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-test/skills/testability-obstacle/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Meu teste do gerador de relatórios escreve no disco real e depende de DateTime.Now. Adicione o menor ponto de costura para que eu possa testá-lo de forma determinística.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente adiciona um ponto de injeção estreito que mantém as chamadas originais funcionando e depois escreve testes determinísticos que usam uma versão falsa dessa dependência.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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
TimeProviderorIFileSystemand asks to migrate call sites to it. Usemigrate-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
Perguntas frequentes
Ela vai redesenhar meu código?
Não. A mudança de produção fica limitada ao que o teste solicitado precisa.
E se a dependência já for injetada?
Então nenhum ponto de costura é necessário, e a skill aponta para escrever testes com uma versão falsa pelo ponto já existente.
Ela migra o projeto inteiro?
Não. Migrações amplas são feitas por uma skill separada.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 5,8 mil
- Posição no ranking
- #14642
- Licença
- MIT
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
create-custom-agent
5,8 milAjuda seu agente a criar arquivos de agentes personalizados para o VS Code, com suas próprias ferramentas, instruções e transferências para outros agentes.
create-skill
5,8 milAjuda seu agente a criar uma nova skill de agente com nome válido, uma descrição clara de quando usá-la e um arquivo SKILL.md que segue o padrão.
csharp-scripts
5,8 milAjuda seu agente a rodar um pequeno programa C# como um único arquivo com a ferramenta de linha de comando do .NET, sem criar um projeto completo.
dotnet-pinvoke
5,8 milAjuda seu agente a chamar corretamente bibliotecas nativas em C ou C++ a partir do .NET, cobrindo assinaturas, tratamento de strings, memória e handles seguros.
Skills parecidas
test-driven-development
311 milEnsina seu agente a escrever primeiro um teste que falha, ver a falha e depois escrever o menor código que passa, antes de criar qualquer funcionalidade ou correção.
verification-before-completion
311 milEnsina seu agente a rodar verificações reais e ler a saída antes de afirmar que uma tarefa, correção ou build está concluído ou passando.
migrate-to-shoehorn
310 milSubstitui conversões de tipo arriscadas nos seus arquivos de teste pela biblioteca shoehorn, para que os testes usem dados parciais e ainda passem na checagem de tipos.