我對 Go 1.18 感到興奮,并想測驗新的泛型特性。使用起來感覺很整潔,但我偶然發現了一個問題:
你如何表測驗泛型函式?
我想出了這段代碼,但我需要在每個函式上重新宣告我的測驗邏輯,因為我無法實體化T值。(在我的專案中,我使用 structs 而不是stringand int。只是不想包含它們,因為它已經足夠的代碼了)
你會如何處理這個問題?
編輯:這是代碼:
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
type Item interface {
int | string
}
type store[T Item] map[int64]T
// add adds an Item to the map if the id of the Item isn't present already
func (s store[T]) add(key int64, val T) {
_, exists := s[key]
if exists {
return
}
s[key] = val
}
func TestStore(t *testing.T) {
t.Run("ints", testInt)
t.Run("strings", testString)
}
type testCase[T Item] struct {
name string
start store[T]
key int64
val T
expected store[T]
}
func testString(t *testing.T) {
t.Parallel()
tests := []testCase[string]{
{
name: "empty map",
start: store[string]{},
key: 123,
val: "test",
expected: store[string]{
123: "test",
},
},
{
name: "existing key",
start: store[string]{
123: "test",
},
key: 123,
val: "newVal",
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]{
{
name: "empty map",
start: store[int]{},
key: 123,
val: 456,
expected: store[int]{
123: 456,
},
},
{
name: "existing key",
start: store[int]{
123: 456,
},
key: 123,
val: 999,
expected: store[int]{
123: 456,
},
},
}
for _, tc := range tests {
t.Run(tc.name, runTestCase(tc))
}
}
func runTestCase[T Item](tc testCase[T]) func(t *testing.T) {
return func(t *testing.T) {
tc.start.add(tc.key, tc.val)
assert.Equal(t, tc.start, tc.expected)
}
}
uj5u.com熱心網友回復:
我需要在每個函式上重新宣告我的測驗邏輯
正確的。
您的函式runTestCase[T Item](tc testCase[T])已經提供了合理的抽象級別。正如您所做的那樣,您可以在其中放置一些關于開始測驗和驗證預期結果的通用邏輯。然而,僅此而已。
被測驗的泛型型別(或函式)遲早必須用一些具體型別實體化,并且一個單獨的測驗表只能包含其中一種型別 - 或interface{}/ any,您不能使用它來滿足特定約束,例如int | string.
但是,您可能不需要總是測驗每個可能的型別引數。泛型的目的是撰寫適用于任意型別的代碼,特別是約束的目的是撰寫支持相同操作的任意型別的代碼。
我建議僅當代碼使用具有不同含義的運算子時才為不同型別撰寫單元測驗。例如:
數字(總和)和字串(連接)的運算子- 數字(更大、更小)和字串(按字典順序在之前或之后)的
<and>
另請參閱OP試圖做類似事情的地方
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426114.html
上一篇:Swift代碼找不到資料的符號
