unit-testing - 如何在测试用例中修复“复合文字中缺少类型”
问题描述
我正在尝试为函数 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...
推荐阅读
- javascript - 每个 amchart 切片的自定义渐变颜色
- c++ - SAM 中的 AWS lambda C++ 运行时
- selenium - 如何从 surefire-reports testng-results.xml 获取 jenkins 测试报告链接?
- daml - 无法编译测试 DAML 模块
- angular - 提交表单后,Angular Material 7 错误重置自动完成
- java - Jave 类型参数方法和构造函数问题
- python - bins - 使用年龄的 bin 对列值进行分类
- javascript - 访问 Javascript 脚本中的 C# 对象
- python - 替换和迭代多维 np.matrix 的 x 轴和 y 轴
- html - 为什么我的背景图像动画没有运行?