使用模拟 Shim 测试链代码

此测试方法涉及使用存根 shim.ChaincodeStubInterface 的模拟版本。这样,您可以在将链代码部署到 Oracle Blockchain Platform 之前对其进行一些功能模拟。您还可以使用此库为链代码构建单元测试。

  1. 创建与链代码文件的名称匹配的测试文件。
    例如,如果 car_dealer.go 是智能合同的实际实施代码,则应创建一个名为 car_dealer_test.go 的测试套件,其中包含 car_dealer.go 的所有测试。测试套件文件名应采用 *_test.go 格式。
  2. 创建程序包和 import 语句。
    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 函数
  • GetQueryResult

  • GetHistoryForKey

不受支持,并且尝试调用其中任何一个将导致错误。