Usa un Mock Shim per testare un codice concatenato

Questo metodo di test utilizza una versione simulata dello stub shim.ChaincodeStubInterface. In questo modo puoi simulare alcune funzionalità del tuo codice concatenato prima di distribuirlo su Oracle Blockchain Platform. È inoltre 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. Utilizzare il formato *_test.go per il nome file della suite di test.
  2. Creare il package e importare le istruzioni.
    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")
    
        // Deploy 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 implementate. Le seguenti funzioni stub non sono supportate.
  • GetQueryResult

  • GetHistoryForKey

Il tentativo di chiamare una di queste funzioni causerà un errore.