使用模擬 Shim 測試鏈碼

此測試方法涉及使用 stub shim.ChaincodeStubInterface 的模擬版本。透過此,您可以在將鏈碼部署到 Oracle Blockchain Platform 之前,先模擬部分功能。您也可以使用此程式庫來建立鏈碼的單元測試。

  1. 建立符合鏈碼檔案名稱的測試檔案。
    例如,如果 car_dealer.go 是您智慧合約的實際實作代碼,您會建立一個名為 car_dealer_test.go 的測試套件,其中包含 car_dealer.go 的所有測試。測試套件檔案名稱應為 *_test.go 格式。
  2. 建立您的封裝項目和匯入敘述句。
    package main
    
    import (
        "fmt"
        "testing"
    
        "github.com/hyperledger/fabric/core/chaincode/shim"
    )
  3. 建立您的單元測試。
    /*
    * 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)
        }
    }

附註:

並未實作 stub 的所有介面。Stub 函數
  • GetQueryResult

  • GetHistoryForKey

不支援,且嘗試呼叫其中之一會導致錯誤。