Best practices for Go function testing: well-defined test cases. Use table-driven testing. Cover boundary conditions. Mock dependencies. Use subtest. Measure test coverage.
Best Practices for Function Testing in Go
Function testing in Go is critical to ensuring code reliability. Here are some best practices to help you write powerful function tests:
1. Define clear test cases:
For each function, clearly define the behavior to be tested and expected results. This will help you focus on writing tests that meet your specific testing purpose.
2. Use table-driven testing:
Table-driven testing allows you to make multiple calls to a function using a set of input values. This helps reduce duplicate code and improves readability.
func TestSum(t *testing.T) { type testInput struct { a, b int want int } tests := []testInput{ {1, 2, 3}, {-5, 10, 5}, {0, 0, 0}, } for _, tt := range tests { got := Sum(tt.a, tt.b) if got != tt.want { t.Errorf("got: %d, want: %d", got, tt.want) } } }
3. Cover boundary conditions:
In addition to testing normal conditions, the input boundary conditions must also be tested. This helps uncover potential problems in edge cases.
4. Mock dependencies:
If a function depends on external dependencies, use mocking technology to isolate these dependencies. This ensures that we are testing the function itself and not its dependencies.
import ( "testing" "github.com/golang/mock/gomock" ) func TestGetUserData(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockUserDataRepository := mock_user_data_repository.NewMockUserDataRepository(ctrl) userDataService := NewUserDataService(mockUserDataRepository) userID := 10 expectedData := user_data.UserData{Name: "John Doe"} mockUserDataRepository.EXPECT().Get(userID).Return(expectedData, nil) data, err := userDataService.GetUserData(userID) if err != nil { t.Errorf("unexpected error: %v", err) } if data != expectedData { t.Errorf("unexpected data: %v", data) } }
5. Use subtests:
Large function tests can be broken down into smaller subtests. This helps organize your code and improve readability.
func TestSort(t *testing.T) { t.Run("empty array", func(t *testing.T) { arr := []int{} arrayCopy := Sort(arr) if !reflect.DeepEqual(arr, arrayCopy) { t.Errorf("sorting empty array results in a new array") } }) }
6. Measure test coverage:
Use coverage tools to measure the coverage of code by tests. This helps identify untested code paths and improves test coverage.
By following these best practices, you can write more efficient and reliable tests for your Go functions.
The above is the detailed content of Best practices for Golang function testing. For more information, please follow other related articles on the PHP Chinese website!