Pular para o conteúdo principal

Testes

Testes unitários são fundamentais para a qualidade do software. Veja como diferentes linguagens lidam com testes usando seus frameworks embutidos ou mais populares.

Testes Unitários Básicos​

// Jest (most popular)
// npm install --save-dev jest

// math.js
function add(a, b) { return a + b; }
module.exports = { add };

// math.test.js
const { add } = require('./math');

describe('add', () => {
test('adds two numbers', () => {
expect(add(1, 2)).toBe(3);
});

test('handles negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});

test('handles zero', () => {
expect(add(0, 0)).toBe(0);
});
});

// Run: npx jest

Mocking & Testes Avançados​

// Jest mocking
jest.mock('./api');
const api = require('./api');

api.fetchUser.mockResolvedValue({ name: 'John' });

test('fetches user', async () => {
const user = await getUser(1);
expect(api.fetchUser).toHaveBeenCalledWith(1);
expect(user.name).toBe('John');
});

// Spies
const spy = jest.spyOn(console, 'log');
doSomething();
expect(spy).toHaveBeenCalledWith('expected');

// Async testing
test('async operation', async () => {
await expect(fetchData()).resolves.toBe('data');
await expect(failOp()).rejects.toThrow('error');
});

Principais Conclusões​

  • Frameworks embutidos vs externos -- Rust, Go e Zig vêm com test runners embutidos; JavaScript, Python, PHP e C++ dependem de ferramentas externas (Jest, pytest, PHPUnit, Google Test).
  • Estilos de asserção diferem -- Go usa if got != want { t.Errorf(...) } manual; xUnit/Jest usam Assert.Equal/expect().toBe; RSpec e FluentAssertions favorecem estilo BDD expect(x).to eq(y).
  • Abordagens de mocking variam -- Mocking baseado em interface é comum em Go e Swift; Java/C# usam Mockito/Moq; Python usa unittest.mock; Rust usa crates como mockall com mocks baseados em traits.
  • Testes parametrizados são idiomáticos em alguns ecossistemas -- Go favorece testes orientados a tabela; xUnit usa [Theory] e [InlineData]; JUnit 5 e Swift Testing têm @ParameterizedTest e @Test(arguments:).
  • Testes de performance são embutidos em Go -- go test -bench=. executa benchmarks; outras linguagens tipicamente usam ferramentas separadas (pytest-benchmark, criterion para Rust, etc.).