示例#1
0
    public void WritesModelFactoryBody()
    {
        var parentModel = root.AddClass(new CodeClass {
            Name = "parentModel",
            Kind = CodeClassKind.Model,
        }).First();
        var childModel = root.AddClass(new CodeClass {
            Name = "childModel",
            Kind = CodeClassKind.Model,
        }).First();

        (childModel.StartBlock as ClassDeclaration).Inherits = new CodeType {
            Name           = "parentModel",
            TypeDefinition = parentModel,
        };
        var factoryMethod = parentModel.AddMethod(new CodeMethod {
            Name       = "factory",
            Kind       = CodeMethodKind.Factory,
            ReturnType = new CodeType {
                Name           = "parentModel",
                TypeDefinition = parentModel,
            },
            IsStatic = true,
        }).First();

        factoryMethod.AddDiscriminatorMapping("ns.childmodel", new CodeType {
            Name           = "childModel",
            TypeDefinition = childModel,
        });
        factoryMethod.DiscriminatorPropertyName = "@odata.type";
        factoryMethod.AddParameter(new CodeParameter {
            Name = "parseNode",
            Kind = CodeParameterKind.ParseNode,
            Type = new CodeType {
                Name           = "ParseNode",
                TypeDefinition = new CodeClass {
                    Name = "ParseNode",
                },
                IsExternal = true,
            },
            Optional = false,
        });
        var factoryFunction = root.AddFunction(new CodeFunction(factoryMethod)).First();

        writer.Write(factoryFunction);
        var result = tw.ToString();

        Assert.Contains("const mappingValueNode = parseNode.getChildNode(\"@odata.type\")", result);
        Assert.Contains("if (mappingValueNode) {", result);
        Assert.Contains("const mappingValue = mappingValueNode.getStringValue()", result);
        Assert.Contains("if (mappingValue) {", result);
        Assert.Contains("switch (mappingValue) {", result);
        Assert.Contains("case \"ns.childmodel\":", result);
        Assert.Contains("return new ChildModel();", result);
        Assert.Contains("return new ParentModel();", result);
        AssertExtensions.CurlyBracesAreClosed(result, 1);
    }