我正在尝试为功能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)
}
})
}
}
答案 0 :(得分:1)
如错误所示,您需要在声明中包括类型。由于您正在使用匿名类型,因此这意味着您必须重复类型定义。当然,这很烦人:
//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...