【问题标题】:Display xUnit test data from multiple XML files using style sheet使用样式表显示来自多个 XML 文件的 xUnit 测试数据
【发布时间】:2018-03-06 09:35:48
【问题描述】:

我使用 xUnit 编写了一个测试,它使用 MemberData 属性通过此类发现包含测试数据的 XML 文件:

internal class XmlDataRetriever
{
    private const String XmlPath = @"..\..\TestCases\";

    public static IEnumerable<TestCase[]> Data
    {
        get
        {
            return
                CreateTestCases(
                    Directory.GetFiles(XmlPath, "*.xml", SearchOption.TopDirectoryOnly)
                    .ToReadOnlyCollection());
        }
    }

    private static List<TestCase[]> CreateTestCases(ReadOnlyCollection<String> filePaths)
    {
        return
            filePaths
                .Select(testCaseName =>
                    new TestCase[] { new XmlParser().GetTestCase(testCaseName) })
                .ToList();
    }
}

这里的代码不是那么重要,但它提供了如何发现测试用例的想法。

我希望通过某种方式在一个文档中查看这些 XML 测试用例的列表,最好是在 Visual Studio 中,但我不确定实现此目的的最佳方式。

我已经研究过使用 XSLT,但这只是成功的一半,因为我仍然需要一些方法来发现测试用例并将它们全部显示出来。

【问题讨论】:

  • 当您有多个 xml 文件附加在一起时(根级别的数组)称为“格式不正确”,尽管它符合 xml 标准。我有时会创建一个虚拟根元素:(在此处添加文件),然后将所有单独的 xml 文件添加到根。
  • 这是个好主意。不过,我仍然需要某种自动化过程来编译这个父 XML。
  • 我通常只是使用streamreader读取文件并跳过每个文件的第一行(标识行),然后在根元素下合并。做起来很简单。将发布示例。

标签: c# xml visual-studio xslt xunit


【解决方案1】:

这里是结合xml文件的例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        private const String XmlPath = @"..\..\TestCases\";
        static void Main(string[] args)
        {
            string xml = "<Root>";
            foreach (string file in Directory.GetFiles(XmlPath))
            {
                StreamReader reader = new StreamReader(file, Encoding.UTF8);
                //skip identification line
                reader.ReadLine();
                xml += reader.ReadToEnd();
            }

            xml += "</Root>";
        }
    }
}

如果您想使用 xml linq,请尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        private const String XmlPath = @"..\..\TestCases\";
        static void Main(string[] args)
        {
            XElement xRoot = new XElement("Root");
            foreach (string file in Directory.GetFiles(XmlPath))
            {
                XDocument doc = XDocument.Load(file);
                XElement root = doc.Root;
                xRoot.Add(root);
            }

        }
    }

【讨论】:

  • 我可能最终会这样做,但理想情况下,我想要一种在任何编译代码之外执行此操作的方法。我希望能够以某种方式托管一个整理所有 XML 文件的文档。在我们的团队中让非技术人员从 VS 运行控制台应用程序在现阶段有点太过分了。我想我可以尝试将您的想法用作构建过程的一部分。绝对是要研究的东西。谢谢!
  • 你可以创建一个bat文件来做同样的事情。
猜你喜欢
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2016-11-28
  • 1970-01-01
相关资源
最近更新 更多