Automation Test Practice

Follow me on GitHub

Data Driven Test in xUnit Using Custom Attribute

There are couple of different Unit Test framework for C#. xUnit is one of the best one with latest technology.

xUnit has Theory attribute together with InlineData attribute to support simple parameterized test case. However in real automation test, we normally have large amount test data stored in external source, like a csv file. We need automatially load these test data from the csv file to the test method. A custom Attribute can help to achieve this goal. To check xUnit source code, we can see there is an ExcelDataAttribute class which can load test data from excel file. We normally don’t sugest to use excel format file to save test data, thus we can learn from that class and write a CsvDataAttribute.

The csv file we use in this example:

TestCase ID,firstName,middleName,lastName
001,TCTTYYY,YYY,YYYQYNADYXC
002,TCTTYNN,YYY,YYYQYNADYXC

xunit_1.png

xunit_2.png

You may have observed there is yield return keyword used. What’s the advantage of using yield here? I may open another post to discuss it later.

The CsvData attribute extends from DataAttribute. DataAttribute is an abstract class from xUnit SDK and it extends from Attribute directly.
xunit_3.png

In terms of the test data file path, I use relative file path. Thus in the project file, make sure cope the test data file to relevant output directory. You can add follow onto the ItemGroup section.

<Content Include=”test_data.csv”>   
<CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content>

We can test attribute as following.

[Theory, CsvData(true)]
public void Test6(String testCaseId, String firstName, String lastName)
{
Assert.Equal(Hello, $”{testCaseId}: {firstName} _ {lastName});
}

Normally we don’t need the TestCaseId in the test method, you can try to modify the attribute class to skip the 1st column.

Back To Homepage