![](/img/trans.png)
[英]How to set composite type array containing JSONB elements with a literal value?
[英]How to fix “missing type in composite literal” in test cases
我正在嘗試為功能ReadField()編寫測試代碼,但是在定義測試用例時遇到了困難。
它給出一個錯誤“復合文字中缺少類型”。 我相信它只是一些語法錯誤。
我嘗試過在函數體之外定義結構,但仍會給出相同的錯誤。
ReadField(string, string, bool) (bool, string)
func TestReadField(t *testing.T){
testCases := []struct {
Name string
Input struct{
FirstString string
SecondString string
SomeBool bool
}
Expected struct{
IsValid bool
Message string
}
}{
//This is where the error points to.
//Valid
{"Test Case 1",
//Missing type error
{"FirstString", "SecondString", true},
//Missing type error
{true, "testMessage"},},
//Same goes for the remaining
{"Test Case 2",
{"FirstString", "SecondString", false},
{true, "testMessage"},},
{"Test Case 3",
{"FirstString", "SecondString", true},
{false, "testMessage"},},
}
for _, testCase := range testCases{
t.Run(testCase.Name, func(t *testing.T){
isValid, message := ReadField(testCase.Input.FirstString, testCase.Input.SecondString, testCase.Input.SomeBool)
if isValid != testCase.Expected.IsValid || message != testCase.Expected.Message {
t.Errorf("Expected: %b, %b \n Got: %b, %b", testCase.Expected.IsValid, testCase.Expected.Message, isValid, message)
} else {
t.Logf("Expected: %b, %b \n Got: %b, %b", testCase.Expected.IsValid, testCase.Expected.Message, isValid, message)
}
})
}
}
如錯誤所示,您需要在聲明中包括類型。 由於您正在使用匿名類型,因此這意味着您必須重復類型定義。 當然,這很煩人:
//Valid
{"Test Case 1",
//Missing type error
struct{
FirstString string
SecondString string
SomeBool bool
}{"FirstString", "SecondString", true},
// etc ...
因此,您應該使用命名類型:
type testInput struct{
FirstString string
SecondString string
SomeBool bool
}
type expected struct{
IsValid bool
Message string
}
testCases := []struct {
Name string
Input testInput
Expected expected
}{
//Valid
{"Test Case 1",
//Missing type error
testInput{"FirstString", "SecondString", true},
// etc ...
或者(根據我的喜好),將頂層結構展平,使所有內容可讀性更高:
testCases := []struct {
Name string
InputFirstString string
InputSecondString string
InputSomeBool bool
IsValid bool
Message string
}{
//Valid
{"Test Case 1",
"FirstString",
"SecondString",
true,
// etc...
我也強烈建議您在定義中使用字段標簽,以提高可讀性:
//Valid
{
Name: "Test Case 1",
InputFirstSTring: "FirstString",
InputSecondString: "SecondString",
InputSomeBool: true,
// etc...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.