Home >Backend Development >Golang >How Can We Effectively Table Test Generic Functions in Go Without Instantiating Type Parameters?
Challenge:
Go 1.18 introduces generics, but how can you effectively table test generic functions when instantiation is not possible for T values?
Problem Statement:
Current testing methods require redeclaring testing logic for each function due to the inability to instantiate T values.
Approach:
The testing approach should focus on reusing common logic while considering the specific nature of generic functions.
Solution:
1. Reusable Testing Logic:
Create a generic testing function, such as runTestCase[T Item](tc testCase[T]), that encapsulates common operations like setting up tests and verifying results.
2. Instantiation Consideration:
Generic functions must eventually be instantiated with specific types. However, it's not necessary to test every possible type parameter.
3. Focus on Type-Specific Behavior:
Concentrate on testing functions for specific types only if their behaviors differ based on operator semantics. For example, the operator for numbers and strings, or comparison operators for numbers and strings.
Example:
This test code employs the generic runTestCase function to test different types of values in a store map:
func TestStore(t *testing.T) { t.Run("ints", testInt) t.Run("strings", testString) } func testString(t *testing.T) { t.Parallel() tests := []testCase[string]{ { start: store[string]{}, key: 123, val: "test", expected: store[string]{123: "test"}, }, // ... } for _, tc := range tests { t.Run(tc.name, runTestCase(tc)) } } func testInt(t *testing.T) { t.Parallel() tests := []testCase[int]{ { start: store[int]{}, key: 123, val: 456, expected: store[int]{123: 456}, }, // ... } for _, tc := range tests { t.Run(tc.name, runTestCase(tc)) } }
The above is the detailed content of How Can We Effectively Table Test Generic Functions in Go Without Instantiating Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!