ZhangZhihui's Blog  

 

=== RUN   TestTransferTx
    store_test.go:87: 
        	Error Trace:	/home/runner/work/zimplebank/zimplebank/db/sqlc/store_test.go:87
        	Error:      	Not equal: 
        	            	expected: 20
        	            	actual  : 19.999999999999943
        	Test:       	TestTransferTx
--- FAIL: TestTransferTx (0.68s)

 

        // check balances
        diff1 := account1.Balance - fromAccount.Balance
        diff2 := toAccount.Balance - account2.Balance
        require.Equal(t, diff1, diff2)

The above assertion succeeds most of time, but it really fails occassionaly. The cause is that we can't compare two float numbers directly.

Change the code as below:

        // check balances
        diff1 := account1.Balance - fromAccount.Balance
        diff2 := toAccount.Balance - account2.Balance
        require.LessOrEqual(t, math.Abs(diff1 - diff2), 1e-10)

 

posted on 2023-12-31 11:03  ZhangZhihuiAAA  阅读(16)  评论(0编辑  收藏  举报