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