Exercício – Testar seu contrato inteligente

Concluído

Nesta parte, vamos gravar um novo teste JavaScript para nosso contrato de remessa. Poderíamos, como alternativa, usar Solidity para gravar o teste, mas o JavaScript é mais comum. Para testar nosso contrato inteligente, vamos usar o Truffle.

Iniciar o teste

Vamos começar criando um arquivo de teste.

  1. No painel do Explorador, passe o ponteiro do mouse sobre a pasta teste e clique com o botão direito do mouse. Escolha Novo Arquivo e crie um arquivo chamado TestShipping.js.

  2. Copie e cole o código a seguir no arquivo de teste:

    const ShippingStatus= artifacts.require("./Shipping.sol");
    contract('Shipping', () => {
    
      it("should return the status Pending", async ()=> {
        // Instance of our deployed contract
        const instance = await ShippingStatus.deployed();
        // Checking the initial status in our contract
        const status = await instance.Status();
        // Checking if the status is initially Pending as set in the constructor
        assert.equal(status, "Pending");
      });
    it("should return the status Shipped", async ()=> {
    // Instance of our deployed contract
        const instance = await ShippingStatus.deployed();
    
        // Calling the Shipped() function
        await instance.Shipped();
    
        // Checking the initial status in our contract
        const status = await instance.Status();
    
        // Checking if the status is Shipped
        assert.equal(status, "Shipped");
      });
    
        it("should return the status Delivered", async ()=> {
    
        // Instance of our deployed contract
        const instance = await ShippingStatus.deployed();
    
        // Calling the Shipped() function
        await instance.Delivered();
    
        // Checking the initial status in our contract
        const status = await instance.Status();
    
        // Checking if the status is Delivered
        assert.equal(status, "Delivered");
      });
    });
    

Teste de evento

Usaremos o pacote truffle-assertions para testar os eventos que são enviados no contrato. Usando esse pacote, podemos ter certeza de que nossos eventos são emitidos durante a transação.

  1. No terminal, instale a biblioteca digitando npm install truffle-assertions.

  2. Adicione o seguinte código ao arquivo de teste na linha 2, após solicitar o contrato ShippingStatus:

    const truffleAssert = require('truffle-assertions');
    
  3. Adicione um teste para confirmar se o evento retorna a descrição esperada. Posicione esse teste após o último teste no arquivo. Adicione-o a uma nova linha, imediatamente antes do conjunto de chaves de encerramento da última linha.

      it('should return correct event description', async()=>{
    
        // Instance of our deployed contract
        const instance = await ShippingStatus.deployed();
    
        // Calling the Delivered() function
        const delivered = await instance.Delivered();
    
        // Check event description is correct
        truffleAssert.eventEmitted(delivered, 'LogNewAlert', (event) =>{
          return event.description == 'Your package has arrived';
        });
      });
    
    

Usar async/await

A função .deployed() retorna uma promessa. Por isso, usamos await diante da função e async diante do código de teste. Essa configuração significa que, após a implantação do contrato, só prosseguiremos com nosso teste quando a promessa for cumprida.

Esse padrão é normalmente usado em testes porque quase todas as transações de contratos inteligentes são assíncronas, já que precisam ser validadas ou mineradas antes de serem adicionadas à razão do blockchain.

No geral, você deve visar uma cobertura de teste de 100% para seu contrato, especialmente se planeja implantá-lo na rede principal do Ethereum ou Rede Principal.

Executar o teste

No terminal, digite:

truffle test

Todos os testes devem ter êxito:

  Contract: HelloBlockchain
    ✓ testing ResponseMessage of HelloBlockchain
    ✓ testing Responder of HelloBlockchain
    ✓ testing RequestMessage of HelloBlockchain
    ✓ testing State of HelloBlockchain
    ✓ testing Requestor of HelloBlockchain
    ✓ testing SendRequest of HelloBlockchain (51ms)
    ✓ testing SendResponse of HelloBlockchain (46ms)

  Contract: Shipping
    ✓ should return the status Pending
    ✓ should return the status Shipped (59ms)
    ✓ should return the status Delivered (58ms)
    ✓ should return correct event description (39ms)