Data Driven Test on Visual Studio using a complex

2019-08-08 14:53发布

问题:

I wonder if what I want to do is possible. I have a unit test driven by a xml, as follow :

[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", 
            "|DataDirectory|\\MyFile.xml", 
            "TestMember", 
            DataAccessMethod.Sequential)]
[DeploymentItem("MyFile.xml")]
[TestMethod]
public void Hello()
{
    ...
}

where MyFile.xml looks like this :

<TestMembers>
  <TestMember>
    <Name>Hello</Name>
    <id>1234</id>
    <MyComplexRow>
      <MySerializedInstanceOfClass>
        <BooleanProperty>true</BooleanProperty>
        <IntProperty>8</IntProperty>
        <MySerializedInstanceOfAnotherClass>
          <int>23</int>
          <bool>false</bool>
          <double>8.0</double>
        </MySerializedInstanceOfAnotherClass>
      </MySerializedInstanceOfClass>
    </MyComplexRow>
  </TestMember>
</TestMembers>

Now the problem is that accessing TestContext.DataRow["Name"] works fine, but I can't access the TestContext.DataRow["MyComplexRow"], I get a Column 'MyComplexRow' does not belong to table TestMember. because it's not a "scalar", but has many dimensions...

So, is there any way I could trick Visual Studio to let him know he's dealing with a serialized instance of an existing class ? Like, extending an existing class perhaps.

I know I could wrap it all up in CDATA and then deserialize it, but, well, it's not as elegant.

Thanks !

回答1:

I suggest using XUnit and XUnit.Extensions, both available through nuget.

Decorating a test method as a [Theory] and [ClassData] will let you specify a source as complex as you wish, letting you to deal how you wish to deserialize (in this here case) your XML source. You can then inject the expected results as parameters of your test method. You will also loop through "rows" of objects, and again it's up to you to define what you want to treat as a row.

Hmm, I'm not certain it's very comprehensible, but you should take a look at this small blog post, it clearly explains with examples how you deal with it.

Conclusion: XUnit is a great testing framework, and will integrate nicely with Visual Studio test panel and such. Syntax is also mostly the same. Plus, it's free.