Boas práticas em Testes Unitários e Integrados


Garantindo Qualidade, Manutenibilidade e Confiabilidade no Código
Os testes são essenciais para qualquer aplicação robusta. Saber quando usar testes unitários, quando usar testes de integração e como escrever bons testes evita retrabalho, falhas em produção e códigos difíceis de manter.
Testa uma única unidade isolada (método, classe), sem dependências externas.
Características:
Testa o comportamento real entre módulos: banco, API, repositórios, serviços.
Características:
| Cenário | Tipo recomendado |
|---|---|
| Lógica pura | Unitário |
| Regras com dependências | Unitário com mocks |
| Consultas reais ao banco | Integração |
| Comunicação externa | Integração |
| Fluxos completos | Integração |
Formato: Método_Situação_ResultadoEsperado
Exemplo:
Should_Return_TotalPrice_When_QuantityIsValid()
// Arrange var service = new OrderService(); // Act var result = service.CalculateTotal(10, 5); // Assert Assert.Equal(50, result);
Mocks demais tornam o teste frágil.
Sem hora atual, random, chamadas externas reais.
Ex.: criar → salvar → buscar → validar
Bons testes:
Testes não são sobre quantidade, mas sobre qualidade e clareza.
Ensuring Quality, Maintainability, and Reliability in Code
Tests are essential for any robust application. Knowing when to use unit tests, when to use integration tests, and how to write good tests avoids rework, production failures, and hard-to-maintain code.
Tests a single isolated unit (method, class), without external dependencies.
Characteristics:
Tests the real behavior between modules: database, API, repositories, services.
Characteristics:
| Scenario | Recommended Type |
|---|---|
| Pure logic | Unit |
| Rules with dependencies | Unit with mocks |
| Real database queries | Integration |
| External communication | Integration |
| Complete flows | Integration |
Format: Method_Situation_ExpectedResult
Example:
Should_Return_TotalPrice_When_QuantityIsValid()
// Arrange var service = new OrderService(); // Act var result = service.CalculateTotal(10, 5); // Assert Assert.Equal(50, result);
Too many mocks make the test fragile.
No current time, random, real external calls.
Ex.: create → save → fetch → validate
Good tests:
Tests are not about quantity, but about quality and clarity.