Use a Mock Shim to Test a Chaincode

This method of testing uses a mock version of the shim.ChaincodeStubInterface stub. With this you can simulate some functionality of your chaincode before deploying it to Oracle Blockchain Platform. You can also use this library to build unit tests for your chaincode.

  1. Create a test file that matches the name of the chaincode file.
    For example, if car_dealer.go is the actual implementation code for you smart contract, you would create a test suite called car_dealer_test.go containing all the tests for car_dealer.go. Use the *_test.go format for the test suite file name.
  2. Create your package and import statements.
    package main
    
    import (
        "fmt"
        "testing"
    
        "github.com/hyperledger/fabric/core/chaincode/shim"
    )
  3. Create your unit test.
    /*
    * 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)
        }
    }

Note:

Not all interfaces of the stub are implemented. The following stub functions are not supported.
  • GetQueryResult

  • GetHistoryForKey

Attempting to call either of these functions will result in an error.