Escrevendo e Executando Testes de Contratos
Escreva testes automatizados para seus contratos inteligentes, para detectar erros antes de implantá-los em uma rede ativa.
Escrevendo e Executando Testes de Contratos é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Test Smart Contracts?
Deployed contract code is immutable and often holds real value. A bug can be unfixable and costly. Automated tests let you verify behavior repeatedly and safely before any deployment.
The Test Toolkit
Hardhat and Truffle integrate test runners. Hardhat commonly uses Mocha with the Chai assertion library and ethers.js to deploy and call contracts in tests.
Test File Layout
Tests live in the test/ folder. Each file describes a contract with describe blocks and individual cases with it blocks.
describe("Counter", function () {
it("starts at zero", async function () {
// ...
});
});Deploying in a Test
Before each test you deploy a fresh contract instance so tests stay isolated and do not affect each other.
const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();Making Assertions
Call a contract function and assert the result with Chai. Reading the returned value confirms the contract behaves as expected.
expect(await counter.value()).to.equal(0);
await counter.increment();
expect(await counter.value()).to.equal(1);Testing Reverts
Good tests also confirm failures. Assert that a call reverts with the expected reason when given invalid input.
await expect(counter.setOwner(addr)).to.be.revertedWith("Not owner");Testing Events
Verify that a function emits the right event with the right arguments. Events are how off-chain apps learn about state changes.
await expect(counter.increment())
.to.emit(counter, "Incremented")
.withArgs(1);Working with Multiple Accounts
Test access control by calling functions from different signers. Connect a contract to another account to simulate a non-owner trying a restricted action.
const [owner, other] = await ethers.getSigners();
await expect(counter.connect(other).reset())
.to.be.reverted;Manipulating Time and State
Test runners can fast-forward block time and mine blocks, letting you test time-locked logic without waiting. This is essential for vesting or auction contracts.
Measuring Coverage
A coverage tool reports which lines and branches your tests exercise. Aim for high coverage on critical paths, especially money-moving functions and access checks.
npx hardhat coverageRunning the Suite
Run all tests with a single command. Integrate this into CI so every change is verified automatically before merge or deploy.
npx hardhat testQuick Check
Check your contract testing knowledge.
Recap
You learned to test contracts:
- Use Mocha/Chai with ethers in the
test/folder - Deploy a fresh instance and assert return values
- Test reverts, events, and multiple accounts
- Manipulate time, measure coverage, and run in CI
A solid test suite is your best defense against costly on-chain bugs.
Perguntas Frequentes
A aula “Escrevendo e Executando Testes de Contratos” é grátis?
Sim — o texto completo de “Escrevendo e Executando Testes de Contratos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.
O que vou aprender em “Escrevendo e Executando Testes de Contratos”?
Escreva testes automatizados para seus contratos inteligentes, para detectar erros antes de implantá-los em uma rede ativa. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?
Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Escrevendo e Executando Testes de Contratos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?
Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Configuração do Hardhat ou Truffle
- Compilação e implantação de contratos
- Interação com contratos implantados
- Escrevendo e Executando Testes de Contratos