コード例 #1
0
        public async Task SaveToFileTestAsync()
        {
            var document = new Document()
                           .Html
                           .AddAttribute(a => a.Lang).Setup(l => l.SetValue("en"))
                           .AddAttribute(a => a.ItemScope).Setup(@is => @is.SetValue(true))
                           .AddAttribute(a => a.ItemType).Setup(it => it.SetValue("https://schema.org"))
                           .Document.Head
                           .AddChild(e => e.Link)
                           .AddAttribute(a => a.Rel).Setup(r => r.SetValue("main.css"))
                           .Document.Body
                           .AddChild(e => e.Header)
                           .AddChild(e => e.Div)
                           .AddAttribute(d => d.Class).Setup(cls => cls.SetValue("main_container"))
                           .AddCustomChild("custom_tag")
                           .AddAttribute(ct => ct.AccessKey).Setup(ak => ak.SetValue("custom_key"))
                           .AddCustomAttribute("custom_attribute", "custom_attribute")
                           .AddContent("Text in custom element")
                           .Parent
                           .AddChild(i => i.Img)
                           .Parent.Parent.Parent
                           .AddChild(e => e.Footer)
                           .Document
            ;

            using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                using (var streamWriter = new StreamWriter(fileStream))
                {
                    var serializer = new HtmlSerializer(document);
                    await serializer.SerializeAsync(streamWriter).ConfigureAwait(false);

                    await streamWriter.FlushAsync().ConfigureAwait(false);

                    streamWriter.Close();
                }
            }

            var testHtmlText =
                @"<!DOCTYPE html>
<html lang=""en"" itemscope itemtype=""https://schema.org"">
    <head>
        <link rel=""main.css""/>
    </head>
    <body>
        <header>
            <div class=""main_container"">
                <custom_tag accesskey=""custom_key"" custom_attribute=""custom_attribute"">Text in custom element</custom_tag>
                <img/>
            </div>
        </header>
        <footer/>
    </body>
</html>";
            var result = string.Empty;

            using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                using (var streamReader = new StreamReader(fileStream))
                {
                    result = await streamReader.ReadToEndAsync().ConfigureAwait(false);

                    streamReader.Close();
                }
            }

            Assert.AreEqual(result, testHtmlText);
        }