首页 > 解决方案 > 如何在测试用例中修复“复合文字中缺少类型”

问题描述

我正在尝试为函数 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)
            }
        })  
    }
}

标签: unit-testinggostructcomposite-literals

解决方案


如错误所示,您需要在声明中包含类型。由于您使用的是匿名类型,这意味着您必须重复类型定义。当然,这非常烦人:

    //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...

推荐阅读