Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// math/math.go package math import "errors" func Divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } // math/math_test.go package math_test import ( "math" // standard library math for comparison "testing" mymath "github.com/example/app/math" ) func TestDivide(t *testing.T) { t.Parallel() tests := []struct { name string a, b float64 want float64 wantErr bool }{ {"positive", 10, 2, 5, false}, {"negative divisor", -6, 3, -2, false}, {"float", 1, 3, 1.0 / 3.0, false}, {"divide by zero", 5, 0, 0, true}, } for _, tc := range tests { tc := tc // capture range variable t.Run(tc.name, func(t *testing.T) { t.Parallel() got, err := mymath.Divide(tc.a, tc.b) if (err != nil) != tc.wantErr { t.Errorf("Divide(%v, %v) error = %v, wantErr %v", tc.a, tc.b, err, tc.wantErr) return } if !tc.wantErr && math.Abs(got-tc.want) > 1e-9 { t.Errorf("Divide(%v, %v) = %v, want %v", tc.a, tc.b, got, tc.want) } }) } }
Result
Open