简体   繁体   中英

How can i use DataTable as a data source for my test case using mstest or nunit?

I have a data table which contains the data and i want to use data table as a parameter for my test case as a data driven testing.

Any Testing Framework (MsTest/Nunit) suggestion is appreciated with c# as a scripting language.

Scenario:-

I need to get the test data from TFS which i am able to retrieve and store it in a data table. Once i have saved in data table i need to use the same data table in my test case as a parameter so that my test case runs for all the parameter.

    [DataTestMethod]
    [WorkItem(13)]
    public void GetTestValuesFromTestParameter()
    {
        //Code to get the data from TFS
       var method = MethodBase.GetCurrentMethod();
       var attr = (WorkItemAttribute)method.GetCustomAttributes(typeof(WorkItemAttribute), true)[0];
       GetTableItemsFromTestCase(workItemId);
    }

    private DataTable GetTableItemsFromTestCase(int workItemId)
    {
        //Return the data table items from TFS
    }

Suppose the test case in TFS has 2 parameter [Name,FirstName] and i will prepare the test data with the value

//////Data table Start /////
   [Name] [FirstName] 
 1. ["QWERTY","LAST"] 
 2. ["TEST","TEST"] 
//////Data table END /////

and now i have a data table with 2 rows. The test case should run with 2 input values from data table (i,.e-> 'QWERTY' and 'TEST').

Work item attribute is a mapping to get the ID of the Test case in TFS which will get the data from TFS.

I am struck here and need help on how to pass the Data table to the test case.

A custom ITestDataSource would be needed for this special case

The data source will get the data from TFS and pass that data to the test case.

public class WorkItemAttribute : Attribute, ITestDataSource {
    private readonly int workItemId;

    public WorkItemAttribute(int workItemId) {
        this.workItemId = workItemId;
    }

    public IEnumerable<object[]> GetData(MethodInfo methodInfo) {
        var dataTable = GetTableItemsFromTestCase(workItemId);            
        yield return new object[] { dataTable };
    }

    private DataTable GetTableItemsFromTestCase(int workItemId) {
        //Return the data table items from TFS
    }

    public string GetDisplayName(MethodInfo methodInfo, object[] data) {
        if (data != null)
            return string.Format(CultureInfo.CurrentCulture, "{0} WorkItem {1} - ({2})", methodInfo.Name, workItemId, string.Join(",", data));

        return null;
    }
}

This is like your very own version of DynamicData or DataRow attribute

The test can then use the data source like

[DataTestMethod]
[WorkItem(13)]
public void GetTestValuesFromTestParameter(DataTable data) {
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM