Esercitazione: Testare il contratto intelligente

Completato

In questa sezione si crea un nuovo test JavaScript per il contratto di spedizione. Potremmo usare Solidity per scrivere il test, ma JavaScript è lo strumento comunemente usato a questo scopo. Per testare il contratto intelligente si userà Truffle.

Avviare il test

Per iniziare si creerà un nuovo file di test.

  1. Nel riquadro di esplorazione soffermare il mouse sulla cartella test e fare clic con il pulsante destro del mouse. Scegliere Nuovo file e creare un nuovo file denominato TestShipping.js.

  2. Copiare il codice riportato di seguito e incollarlo nel file di test:

    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");
      });
    });
    

Testare gli eventi

Ora si userà il pacchetto truffle-assertions per testare gli eventi inviati nel contratto. Con questo pacchetto è possibile confermare che gli eventi vengono generati durante la transazione.

  1. Nel terminale installare la libreria digitando npm install truffle-assertions.

  2. Aggiungere il codice seguente al file di test nella riga 2, dopo la richiesta del contratto ShippingStatus:

    const truffleAssert = require('truffle-assertions');
    
  3. Aggiungere un test per confermare che l'evento restituisca la descrizione prevista. Inserire il test dopo l'ultimo test presente nel file. Aggiungerlo in una nuova riga, appena prima del set di parentesi di chiusura dell'ultima riga.

      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';
        });
      });
    
    

Uso di async/await

La funzione .deployed() restituisce una promessa. Pertanto si usa await prima della funzione e async prima del codice di test. Questa configurazione significa che dopo la distribuzione del contratto non si procederà al test fino a quando la promessa non viene soddisfatta.

Questo modello viene usato comunemente nei test, perché quasi tutte le transazioni contratto intelligente sono asincrone. Queste transazioni sono asincrone perché devono essere convalidate o estratte prima di essere aggiunte al libro mastro del blockchain.

Nel complesso, è consigliabile estendere il test al 100% del contratto, specie se si prevede la distribuzione nella rete principale Ethereum o Main Net.

Eseguire il test

Nel terminale digitare:

truffle test

Si noti che tutti i test sono stati superati correttamente:

  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)