LoginSignup
3
2

[Go]不確実性なテストで使える assert.InDelta と assert.InEpsilon の使い方

Last updated at Posted at 2023-11-24

はじめに

Hello wolrd!
今日は testify パッケージの中でも特に便利な assert.InDeltaassert.InEpsilon の使い方について解説します。
これらの関数は、数値の比較テストを行う際に非常に役立ちます。特に、浮動小数点数の精度問題や、小さな誤差を許容する必要があるテストケースに適しています。

assert.InDelta の基本

assert.InDelta は、2つの数値間の差が特定の絶対値(デルタ)以内であることを検証するために使用されます。これは、特に浮動小数点数の計算結果が完全に一致しない場合に便利です。以下の例を見てみましょう。

func TestInDelta(t *testing.T) {
	tests := []struct {
		name     string
		expected interface{}
		actual   interface{}
		delta    float64 // 許容可能な差分の範囲
	}{
		{
			name:     "許容範囲が0、実際の差が0",
			expected: 10,
			actual:   10,
			delta:    0,
		},
		{
			name:     "許容範囲が1、実際の差が1(expected < actual)",
			expected: 10,
			actual:   11,
			delta:    1,
		},
		{
			name:     "許容範囲が1、実際の差が1(expected > actual)",
			expected: 10,
			actual:   9,
			delta:    1,
		},
		{
			name:     "intとfloatの比較もできる",
			expected: int32(10),
			actual:   float64(10.1),
			delta:    0.1,
		},
		{
			name:     "異常系: 許容範囲が1、実際の差が2(expected < actual)",
			expected: 10,
			actual:   12,
			delta:    1,
		},
		{
			name:     "異常系: 許容範囲が1、実際の差が2(expected > actual)",
			expected: 10,
			actual:   8,
			delta:    1,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.InDelta(t, tt.expected, tt.actual, tt.delta)
		})
	}
}

ここで、expected と actual の値の差が delta で指定された範囲内にある場合、テストは成功します。
また、数値の型が異なっていても比較することが可能です。これはInDeltaの中で引数をfloat64に変換しているためです。

assert.InEpsilon の基本

一方、assert.InEpsilon は相対的な差異に注目します。これは、特定の割合(イプシロン)内での数値の近似を検証する際に使用されます。例えば、以下のように使います。

func TestInEpsilon(t *testing.T) {
	tests := []struct {
		name     string
		expected interface{}
		actual   interface{}
		delta    float64 // 許容可能な差分の範囲
	}{
		{
			name:     "許容範囲が10%(期待値としては100 ±10)、実際の差が10",
			expected: 100,
			actual:   110,
			delta:    0.1, // 10%
		},
		{
			name:     "異常系: 許容範囲が10%(期待値としては100 ±10)、実際の差が11",
			expected: 100,
			actual:   111,
			delta:    0.1, // 10%
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.InEpsilon(t, tt.expected, tt.actual, tt.delta)
		})
	}
}

この例では、expected と actual の値が delta で指定された割合内にある場合、テストは成功します。

まとめ

assert.InDelta と assert.InEpsilon は、微小な数値の差異や浮動小数点数の不確実性を扱う際に非常に便利です。これらの関数を使うことで、より柔軟かつ正確な数値比較のテストケースを書くことができます。是非あなたのプロジェクトで活用してみてください!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2