diff --git a/fieldx/schema_test.go b/fieldx/schema_test.go index 151cfed..6c81641 100644 --- a/fieldx/schema_test.go +++ b/fieldx/schema_test.go @@ -426,12 +426,13 @@ func TestSchema_UnmarshalInStruct(t *testing.T) { } } -// TestSchema_Generate_FieldNotFound 测试字段不存在的情况 +// TestSchema_Generate_FieldNotFound 测试 Required 字段不存在时报错 func TestSchema_Generate_FieldNotFound(t *testing.T) { schema := Schema{ "name": Field{ - Type: FieldTypeField, - Value: "nonExistentField", + Type: FieldTypeField, + Value: "nonExistentField", + Required: true, }, } @@ -441,7 +442,35 @@ func TestSchema_Generate_FieldNotFound(t *testing.T) { _, err := schema.Generate(source) if err == nil { - t.Error("Generate() expected error for non-existent field, got nil") + t.Error("Generate() expected error for non-existent required field, got nil") + } +} + +// TestSchema_Generate_OptionalFieldNotFound 测试非 Required 字段不存在时返回 nil 而不报错 +// +// 这是 Required 的另一半语义(见 Field.Required 的文档): 只有 Required 为 true +// 时字段缺失才算错误,否则取到 nil 继续。 +func TestSchema_Generate_OptionalFieldNotFound(t *testing.T) { + schema := Schema{ + "name": Field{ + Type: FieldTypeField, + Value: "nonExistentField", + // Required 默认为 false + }, + } + + source := map[string]any{ + "otherField": "value", + } + + result, err := schema.Generate(source) + if err != nil { + t.Fatalf("Generate() 非必需字段缺失不应报错, 得到: %v", err) + } + if v, ok := result["name"]; !ok { + t.Error("Generate() 应该产出 name 键") + } else if v != nil { + t.Errorf("Generate() name = %v, 期望 nil", v) } }