From dd4c63f252966747a45ec162d756bac09597cf9b Mon Sep 17 00:00:00 2001 From: jmatss Date: Wed, 15 Jun 2022 21:57:24 +0200 Subject: [PATCH] Add tests for nested non-nullable choice members --- XmlSchemaClassGenerator.Tests/XmlTests.cs | 83 +++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/XmlSchemaClassGenerator.Tests/XmlTests.cs b/XmlSchemaClassGenerator.Tests/XmlTests.cs index 33549254..21dd017f 100644 --- a/XmlSchemaClassGenerator.Tests/XmlTests.cs +++ b/XmlSchemaClassGenerator.Tests/XmlTests.cs @@ -1100,6 +1100,89 @@ public void ChoiceMembersAreNullable() Assert.Contains("Opt4Specified", content); } + [Fact] + public void NestedElementInChoiceIsNullable() + { + // Because nullability isn't directly exposed in the generated C#, we use "XXXSpecified" on a value type + // as a proxy. + const string xsd = @" + + + + + + + + + + + + + + + + + +"; + + var generator = new Generator + { + NamespaceProvider = new NamespaceProvider + { + GenerateNamespace = key => "Test" + } + }; + var contents = ConvertXml(nameof(NestedElementInChoiceIsNullable), xsd, generator); + var content = Assert.Single(contents); + + Assert.Contains("ElementASpecified", content); + Assert.Contains("ElementBSpecified", content); + } + + [Fact] + public void OnlyFirstElementOfNestedElementsIsForcedToNullableInChoice() + { + // Because nullability isn't directly exposed in the generated C#, we use the "RequiredAttribute" + // as a proxy. + const string xsd = @" + + + + + + + + + + + + + + +"; + + var generator = new Generator + { + NamespaceProvider = new NamespaceProvider + { + GenerateNamespace = key => "Test" + } + }; + var contents = ConvertXml(nameof(OnlyFirstElementOfNestedElementsIsForcedToNullableInChoice), xsd, generator).ToArray(); + var assembly = Compiler.Compile(nameof(OnlyFirstElementOfNestedElementsIsForcedToNullableInChoice), contents); + + var elementWithChildProperty = assembly.GetType("Test.Root")?.GetProperty("ElementWithChild"); + var nestedChildProperty = assembly.GetType("Test.RootElementWithChild")?.GetProperty("NestedChild"); + Assert.NotNull(elementWithChildProperty); + Assert.NotNull(nestedChildProperty); + + Type requiredType = typeof(System.ComponentModel.DataAnnotations.RequiredAttribute); + bool elementWithChildIsRequired = Attribute.GetCustomAttribute(elementWithChildProperty, requiredType) != null; + bool nestedChildIsRequired = Attribute.GetCustomAttribute(nestedChildProperty, requiredType) != null; + Assert.False(elementWithChildIsRequired); + Assert.True(nestedChildIsRequired); + } + [Fact] public void AssemblyVisibleIsInternalClass() {