-1

How to write a unit test for the following code The GetBook function is a function in chaincode code

func (svc *service) GetBook(_ context.Context, id string) (*Entity, error) {
    res, err := svc.contract.EvaluateTransaction("GetBook", id)
    if err != nil {
        return nil, fmt.Errorf("error on evaluate transaction: %w", err)
    }

    var rsp Entity

    err = json.Unmarshal(res, &rsp)
    if err != nil {
        return nil, fmt.Errorf("error on unmarshal json: %w", err)
    }

    return &rsp, nil
}
bardia
  • 1
  • 1

2 Answers2

1

To run unit test for chaincode, you need to use counterfeiter which you can use to generate all the mock interfaces of contractapi and chaincodeStubs. This can go in your xxxTest.go file

//go:generate counterfeiter -o mocks/transaction.go -fake-name TransactionContext . transactionContext
type transactionContext interface {
    contractapi.TransactionContextInterface
}

//go:generate counterfeiter -o mocks/chaincodestub.go -fake-name ChaincodeStub . chaincodeStub
type chaincodeStub interface {
    shim.ChaincodeStubInterface
}

and import the generated mock interfaces to write unit-test

func TestReadCashWallet(t *testing.T) {
    chaincodeStub := &mocks.ChaincodeStub{}
    transactionContext := &mocks.TransactionContext{}
    transactionContext.GetStubReturns(chaincodeStub)

    cashWalletContract := chaincode.CashWalletContract{}
    cashwallet := &chaincode.CashWallet{
        ID: "id",
    }
    bytes, err := json.Marshal(cashwallet)
    require.NoError(t, err, "error json marshal")

    chaincodeStub.GetStateReturns(bytes, nil)
    res, err := cashWalletContract.ReadCashWallet(transactionContext, "id")
    require.EqualValues(t, cashwallet, res)

}

You have to mock the all the shim functions actions such as GetState, GetHistoryForKey, PutState etc.

More detailed examples are provided in the fabric-samples here. You can clone this and check out the full code example with the usage of counterfeiter and unit test example in the asset-transfer-private-data/chaincode-go

Niraj Kumar
  • 211
  • 2
  • 6
  • I know how to write Chinese test code The following code communicates with Chincode using sdk I wrote a test code for China But I want to write for the following code which is in sdk – bardia Jul 30 '21 at 11:24
-1
import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
    "github.com/hyperledger/fabric-sdk-go/pkg/gateway"
)
func (svc *service) GetBook(_ context.Context, id string) (*Entity, error) {
    res, err := svc.contract.EvaluateTransaction("GetBook", id)
    if err != nil {
        return nil, fmt.Errorf("error on evaluate transaction: %w", err)
    }

    var rsp Entity

    err = json.Unmarshal(res, &rsp)
    if err != nil {
        return nil, fmt.Errorf("error on unmarshal json: %w", err)
    }

    return &rsp, nil
}```
bardia
  • 1
  • 1