英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论