Testing the Init method

First, we need to define the function needed to invoke the Init method. The function will receive references to MockStub, as well as to an array of arguments to pass to the Init method. In line 2 of the following code, the chaincode function Init is invoked with the received arguments, which is then verified in line 3.

The following snippet illustrates the invocation of the Init method:

 func checkInit(t *testing.T, stub *shim.MockStub, args [][]byte) { 
   res := stub.MockInit("1", args) 
   if res.Status != shim.OK { 
         fmt.Println("Init failed", string(res.Message)) 
         t.FailNow() 
   } 
} 

We will now define the function needed to prepare a default array of values of the Init function arguments, shown as follows:

func getInitArguments() [][]byte { 
   return [][]byte{[]byte("init"), 
               []byte("LumberInc"), 
               []byte("LumberBank"), 
               []byte("100000"), 
               []byte("WoodenToys"), 
               []byte("ToyBank"), 
               []byte("200000"),

               []byte("UniversalFreight"), 
               []byte("ForestryDepartment")} 
} 

We will now define the test of the Init function, as shown in the following snippet. The test first creates an instance of the chaincode, then sets the mode to test, and finally creates a new MockStub for the chaincode. In line 7, the checkInit function is invoked and the Init function is executed. Finally, from line 9 onwards, we will verify the state of the ledger, as follows:

func TestTradeWorkflow_Init(t *testing.T) { 
   scc := new(TradeWorkflowChaincode) 
   scc.testMode = true 
   stub := shim.NewMockStub("Trade Workflow", scc) 
 
   // Init 
   checkInit(t, stub, getInitArguments()) 
 
   checkState(t, stub, "Exporter", EXPORTER) 
   checkState(t, stub, "ExportersBank", EXPBANK) 
   checkState(t, stub, "ExportersAccountBalance", strconv.Itoa(EXPBALANCE)) 
   checkState(t, stub, "Importer", IMPORTER) 
   checkState(t, stub, "ImportersBank", IMPBANK) 
   checkState(t, stub, "ImportersAccountBalance", strconv.Itoa(IMPBALANCE)) 
   checkState(t, stub, "Carrier", CARRIER) 
   checkState(t, stub, "RegulatoryAuthority", REGAUTH) 
}

Next, we verify whether each key's state is as expected with the checkState function, as shown in the following codeblock:

func checkState(t *testing.T, stub *shim.MockStub, name string, value string) { 
bytes := stub.State[name]
if bytes == nil {
fmt.Println("State", name, "failed to get value")
t.FailNow()
}
if string(bytes) != value {
fmt.Println("State value", name, "was", string(bytes), "and not", value, "as expected")
t.FailNow()
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.94.209