Usa un Mock Shim per testare un codice concatenato

Questo metodo di test prevede l'utilizzo di una versione mock dello stub shim.ChaincodeStubInterface. Con questo puoi simulare alcune funzionalità del tuo codice concatenato prima di distribuirlo su Oracle Blockchain Platform. È anche possibile utilizzare questa libreria per creare test delle unità per il codice concatenato.

  1. Creare un file di test che corrisponda al nome del file del codice concatenato.
    Ad esempio, se car_dealer.go è il codice di implementazione effettivo per lo smart contract, è necessario creare una suite di test denominata car_dealer_test.go contenente tutti i test per car_dealer.go. Il nome file della suite di test deve essere in formato *_test.go.
  2. Creare il package e le istruzioni di importazione.
    package main
    
    import (
        "fmt"
        "testing"
    
        "github.com/hyperledger/fabric/core/chaincode/shim"
    )
  3. Creare il test di unità.
    /*
    * TestInvokeInitVehiclePart simulates an initVehiclePart transaction on the CarDemo cahincode
     */
    func TestInvokeInitVehiclePart(t *testing.T) {
        fmt.Println("Entering TestInvokeInitVehiclePart")
    
        // Instantiate mockStub using CarDemo as the target chaincode to unit test
        stub := shim.NewMockStub("mockStub", new(CarDemo))
        if stub == nil {
            t.Fatalf("MockStub creation failed")
        }
    
        var serialNumber = "ser1234"
    
        // Here we perform a "mock invoke" to invoke the function "initVehiclePart" method with associated parameters
        // The first parameter is the function we are invoking
        result := stub.MockInvoke("001",
            [][]byte{[]byte("initVehiclePart"),
                []byte(serialNumber),
                []byte("tata"),
                []byte("1502688979"),
                []byte("airbag 2020"),
                []byte("aaimler ag / mercedes")})
    
        // We expect a shim.ok if all goes well
        if result.Status != shim.OK {
            t.Fatalf("Expected unauthorized user error to be returned")
        }
    
        // here we validate we can retrieve the vehiclePart object we just committed by serianNumber
        valAsbytes, err := stub.GetState(serialNumber)
        if err != nil {
            t.Errorf("Failed to get state for " + serialNumber)
        } else if valAsbytes == nil {
            t.Errorf("Vehicle part does not exist: " + serialNumber)
        }
    }

Nota

Non tutte le interfacce dello stub sono state implementate. Funzioni Stub
  • GetQueryResult

  • GetHistoryForKey

non sono supportati e il tentativo di richiamare una di queste opzioni comporta un errore.