如何使用stretchr/testify测试十进制数的相等性?

huangapple go评论98阅读模式
英文:

How to test equality of a decimal with stretchr/testify?

问题

我在运行一个单元测试来检查一个decimal值是否与我期望的值相等时遇到了问题。这是我尝试过的代码:

func Test_example(t *testing.T) {
	t.Run("test if two decimals are equal", func(t *testing.T) {
		sum_amount := decimal.NewFromFloat(1000.00)
                          .Add(decimal.NewFromFloat(5000.00))
    
		require.Equal(t, decimal.NewFromFloat32(6000.00), sum_amount))
	})
}

如你所见,sum_amount是一个decimal类型。然而,在测试用例中比较这两个值时,会出现指数等方面的微小差异。

我该如何使用stretchr/testify正确断言这些值相等呢?

例如,这是差异:

Diff:
--- Expected
+++ Actual
@@ -4,6 +4,6 @@
    abs: (big.nat) (len=1) {
-   (big.Word) 6
+   (big.Word) 6000
      }
    }),
- exp: (int32) 3
+ exp: (int32) 0
  }
英文:

I'm having trouble running a unit test to check if a decimal value is what I've expected. This is what I've tried:

func Test_example(t *testing.T) {
	t.Run("test if two decimals are equal", func(t *testing.T) {
		sum_amount := decimal.NewFromFloat(1000.00)
                          .Add(decimal.NewFromFloat(5000.00))
    
		require.Equal(t, decimal.NewFromFloat32(6000.00), sum_amount))
	})
}

As you can see the sum_amount is a decimal. However comparing the two in the test case work out slightly differently with exponents etc.

How do I properly assert that these values are equal with stretchr/testify?

E.g. here's the diff:

Diff:
--- Expected
+++ Actual
@@ -4,6 +4,6 @@
    abs: (big.nat) (len=1) {
-   (big.Word) 6
+   (big.Word) 6000
      }
    }),
- exp: (int32) 3
+ exp: (int32) 0
  }

答案1

得分: 1

你可以使用decimal.Equal来比较值,使用该库返回一个bool值,然后只需测试该结果是否为true

像这样:

require.Equal(t, decimal.NewFromFloat(6000.00).Equal(sum_amount), true)

另外,你可以使用require.True来检查结果是否为true,而不是比较两个值是否相等。

最终结果如下:

require.True(t, decimal.NewFromFloat(6000.00).Equal(sum_amount))
英文:

You can make use of decimal.Equal so that values can be compared using the library to return a bool and then just test if that result is true.

Like this:

require.Equal(t, decimal.NewFromFloat(6000.00).Equal(sum_amount), true)

Also instead of comparing two values for equality you can just check that the result is true using require.True

This is the end result:

require.True(t, decimal.NewFromFloat(6000.00).Equal(sum_amount))

huangapple
  • 本文由 发表于 2022年7月15日 16:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/72991269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定