Data driven tests using nested xml data file

2019-08-07 01:25发布

问题:

I need to write a unit test driven by a data file that contains collections of data. For obvious reasons a csv file isn't appropriate, but XML suggests itself. However I can't seem to get it to work.

Here's a fragment of the data file (only one test record shown):

<?xml version="1.0" encoding="utf-8" ?>
<testData>
  <testRecord>
    <displayColumnNames>
      <name>Include</name>
      <name>SampleInt1</name>
      <name>SampleInt2</name>
      <name>SampleInt3</name>
      <name>SampleInt4</name>
      <name>SampleInt5</name>
    </displayColumnNames>
    <valueColIDs>
      <valueColID>1</valueColID>
      <valueColID>3</valueColID>
      <valueColID>5</valueColID>
    </valueColIDs>
    <calculations>
      <calculation colID ="2"><![CDATA[500 * [:5]]></calculation>
      <calculation colID ="5"><![CDATA[500 * [:2]]></calculation>
    </calculations>
    <expected>
      <item>5</item>
    </expected>
  </testRecord>
</testData>

Basically I expected to be able to read in a number of data collections from each test record (e.g. "displayColumnNames") and iterate over the values in my test. The number of elements in each such collection will vary from test case to test case.

However the immediate stumbling block is my code line:

var displayColumnNames = TestContext.DataRow["displayColumnNames"];

which throws a test-time error "Column 'displayColumnNames' does not belong to table testRecord.".

I can get this to work nicely with simple 'flat' xml data files, but that doesn't help me. Am I attempting something that VS2008 (ie MSTest) cannot handle, or am I doing something stupid?

回答1:

You can use

TestContext.DataRow.GetChildRows("testRecord_displayColumnNames")

to access the nested nodes. The relation name - "testRecord_displayColumnNames" can be modified to go deeper into the xml hierarchy. HTH