Skip to content

biellts/universidade-automatiza / .claude/skills/csharp-xunit

csharp-xunit

Verified

Get best practices for XUnit unit testing, including data-driven tests

Siga AGENTS.md; em conflito, AGENTS.md prevalece. Neste projeto:

  • xUnit + Shouldly (sem FluentAssertions/MSTest); asserções com Shouldly (ShouldBe, ShouldContain) em vez de Assert.*. Erros de negócio via Result (não exceções).
  • Dois projetos: src/tests/Automatiza.WebApi.UnitTests (domínio, sem banco, AAA + Builder) e src/tests/Automatiza.WebApi.IntegrationTests (endpoints contra PostgreSQL real em Testcontainers, via IClassFixture<ApplicationFactory>, com as migrations aplicadas na subida).
  • Sem biblioteca de mock: domínio não precisa, e integração usa o banco real — nunca mocke DbContext ou IConexaoProvider.
  • Os testes de integração de uma classe compartilham o banco: crie dados com sufixo único e filtre por ele; não dependa de tabela vazia.
  • Relógio: use TimeProvider (ou passe o instante como parâmetro) para testes determinísticos; períodos de ranking no horário de Brasília.

XUnit Best Practices

Your goal is to help me write effective unit tests with XUnit, covering both standard and data-driven testing approaches.

Project Setup

  • Use os projetos de teste existentes (Automatiza.WebApi.UnitTests, Automatiza.WebApi.IntegrationTests), organizados por pasta de módulo (Catalogo/...); não crie um projeto de teste por módulo
  • Microsoft.NET.Test.Sdk, xunit, xunit.runner.visualstudio e Shouldly já estão nos dois projetos; Testcontainers.PostgreSql, no de integração
  • Create test classes that match the classes being tested (e.g., CalculatorTests for Calculator)
  • Use .NET SDK test commands: dotnet test for running tests

Test Structure

  • No test class attributes required (unlike MSTest/NUnit)
  • Use fact-based tests with [Fact] attribute for simple tests
  • Follow the Arrange-Act-Assert (AAA) pattern
  • Name tests using the pattern MethodName_Scenario_ExpectedBehavior
  • Use constructor for setup and IDisposable.Dispose() for teardown
  • Use IClassFixture<T> for shared context between tests in a class
  • Use ICollectionFixture<T> for shared context between multiple test classes

Standard Tests

  • Keep tests focused on a single behavior
  • Avoid testing multiple behaviors in one test method
  • Use clear assertions that express intent
  • Include only the assertions needed to verify the test case
  • Make tests independent and idempotent (can run in any order)
  • Avoid test interdependencies

Data-Driven Tests

  • Use [Theory] combined with data source attributes
  • Use [InlineData] for inline test data
  • Use [MemberData] for method-based test data
  • Use [ClassData] for class-based test data
  • Create custom data attributes by implementing DataAttribute
  • Use meaningful parameter names in data-driven tests

Assertions

  • Neste projeto, prefira os equivalentes do Shouldly (ShouldBe, ShouldBeSameAs, ShouldBeTrue, ShouldContain, ShouldMatch) aos Assert.* abaixo
  • Use Assert.Equal for value equality
  • Use Assert.Same for reference equality
  • Use Assert.True/Assert.False for boolean conditions
  • Use Assert.Contains/Assert.DoesNotContain for collections
  • Use Assert.Matches/Assert.DoesNotMatch for regex pattern matching
  • Use Assert.Throws<T> ou await Assert.ThrowsAsync<T> apenas para falhas inesperadas — erro de negócio é Result, verifique com Shouldly (result.Success.ShouldBeFalse())

Mocking and Isolation

  • Teste de domínio não precisa de mock: monte o agregado com o builder de teste
  • Teste de integração usa a API e o PostgreSQL reais (ApplicationFactory), sem mock
  • Tempo entra por TimeProvider (ou pelo instante passado como parâmetro), nunca pelo relógio real

Test Organization

  • Group tests by feature or component
  • Use [Trait("Category", "CategoryName")] for categorization
  • Use collection fixtures to group tests with shared dependencies
  • Consider output helpers (ITestOutputHelper) for test diagnostics
  • Skip tests conditionally with Skip = "reason" in fact/theory attributes
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 197kUpdated Claude CodeCodexVerifiedInstall