Skip to content

NUnit DataDriven tests from Xml, CSV and Excel files

Jakub Raczek edited this page Apr 25, 2019 · 11 revisions

1. NUnit test framework

1.1 Data driven tests from Xml files

Data driven tests from Xml files are not supported with NUnit by default, but you can use DataDrivenHelper class methods from our Test.Automation framework to read xml files and pass test data to your tests.

1.1.1 Just add xml file with test data to your NUnit project e.g:

<?xml version="1.0" encoding="utf-8"?>
<tests>
  <credential user="tomsmith" password="SuperSecretPassword!" message="You logged into a secure area!"/>
  <credential user="wronguser" password="wrongpassword" message="Your username is invalid!"/>
  <links number="3"/>
</tests>

Make sure that file properties "Copy to Output Directory" is set to "Copy always" and proper path (relative) is set to that file in App.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <appSettings>
...
 <add key="DataDrivenFile" value="\DataDriven\DataDriven.xml" />
...
 </appSettings>
</configuration>

1.1.2 Create a class for relation between data driven tests and xml file with test data e.g:

namespace Ocaramba.Tests.NUnit.DataDriven
{
    using System.Collections;

    /// <summary>
    /// DataDriven methods for NUnit test framework
    /// </summary>
    public static class TestData 
    {

        public static IEnumerable Credentials
        {
            get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential", new[] { "user", "password" }, "credential"); }
        }

        public static IEnumerable LinksSetTestName
        {
            get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "links", new[] { "number" }, "Count_links"); }
        }
    }
}

Where calling the method ReadDataDriveFile()

DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "links", new[] { "number" }, "Count_links");

from its definitions:

public static IEnumerable<TestCaseData> DataDrivenHelper.ReadDataDriveFile(string folder, string testData, string[] diffParam, [Optional] string testName);

folder - Full path to XML DataDriveFile file

testData - Name of the child element in xml file

diffParam - Values of listed parameters will be used in test case name

testName - Name of the test, use as prefix for test case name

Definition of class DataDrivenHelper can be found here

1.1.3 Set tests to use test data from xml file e.g:

namespace Ocaramba.Tests.NUnit.Tests
{
    using System.Collections.Generic;

    using global::NUnit.Framework;

    using Ocaramba;
    using Ocaramba.Tests.NUnit.DataDriven;
    using Ocaramba.Tests.PageObjects.PageObjects.TheInternet;

    [TestFixture]
    [Parallelizable(ParallelScope.Fixtures)]
    public class HerokuappTestsNUnit : ProjectTestBase
    {
        [Test]
        [TestCaseSource(typeof(TestData), "Credentials")]
        public void FormAuthenticationPageTest(IDictionary<string, string> parameters)
        {
            new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

            var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
            formFormAuthentication.EnterUserName(parameters["user"]);
            formFormAuthentication.EnterPassword(parameters["password"]);
            formFormAuthentication.LogOn();
            Verify.That(
                this.DriverContext,
                () => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));

        }

        [Test]
        [TestCaseSource(typeof(TestData), "LinksSetTestName")]
        public void CountLinksAtShiftingContentTest(IDictionary<string, string> parameters)
        {
            new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

            var links = new ShiftingContentPage(this.DriverContext);
            Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
        }
    }
}

Where

[TestCaseSource(typeof(TestData), "Credentials")]

TestData is a a class for relation between data driven tests and xml file from 1.1.2

"Credentials" is a method from TestData class.

Names of test are set dynamically by the values of test data read from xml file e.g:

1.1.4 If you want to execute any of your test repeatedly with different test data, just repeat

as many time as you need corresponding child element in xml file

<credential user="tomsmith" password="SuperSecretPassword!" message="You logged into a secure area!"/>
<credential user="wronguser" password="wrongpassword" message="Your username is invalid!"/>

1.1.5 If you don't need to set test case name use overridden method

 public static IEnumerable Links
        {
            get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "links"); }
        }

from its definitions:

public static IEnumerable<TestCaseData> DataDrivenHelper.ReadDataDriveFile(string folder, string testData);

folder - Full path to XML DataDriveFile file

testData - Name of the child element in xml file

and set test use that method "Links"

[Test]
[TestCaseSource(typeof(TestData), "Links")]
public void CountLinksAtShiftingContentTest(IDictionary<string, string> parameters)
 {
      new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

      var links = new ShiftingContentPage(this.DriverContext);
      Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
 }

Names of test remain unchanged e.g:

1.1.6 Examples of implementation can be found here:

1.2 Data driven tests from Excel files

Data driven tests from Excel files are not supported with NUnit by default, but you can use DataDrivenHelper class methods from our Test.Automation framework to read Excel xlsx files and pass test data to your tests. You need to install first NPOI. Test data is passed to the test as parameters (key - name of parameter and key value). You can store test data for several tests at separate Excel sheets. Data in first row at each sheet is used for name of parameters - keys.

1.2.1 Just add Excel xlsx file with test data to your NUnit project e.g

Make sure that file properties "Copy to Output Directory" is set to "Copy always" and proper path (relative) is set to that file in App.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <appSettings>
...
   <add key="DataDrivenFileXlsx" value="\DataDriven\DataDriven.xlsx"/>
...
 </appSettings>
</configuration>

1.2.2 Create a class for relation between data driven tests and xlsx file with test data e.g:

namespace Ocaramba.Tests.NUnit.DataDriven
{
    using System.Collections;

    /// <summary>
    /// DataDriven methods for NUnit test framework
    /// </summary>
    public static class TestData 
    {

        public static IEnumerable CredentialsExcel
        {
            get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "credential", new[] { "user", "password" }, "credentialExcel"); }
        }

        public static IEnumerable LinksExcel
        {
            get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "links"); }
        }
    }
}

Where calling the method ReadXlsxDataDriveFile()

DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "credential", new[] { "user", "password" }, "credentialExcel");

from its definitions:

 public static IEnumerable<TestCaseData> ReadXlsxDataDriveFile(string path, string sheetName, [Optional] string[] diffParam, [Optional] string testName)

path - Full path to Excel DataDriveFile file

sheetName - Name of the sheet at xlsx file.

diffParam - Optional values of listed parameters will be used in test case name.

testName - Optional name of the test, use as prefix for test case name.

Definition of class DataDrivenHelper can be found here

1.2.3 Set tests to use test data from xlsx file e.g:

namespace Ocaramba.Tests.NUnit.Tests
{
    using System.Collections.Generic;

    using global::NUnit.Framework;

    using Ocaramba;
    using Ocaramba.Tests.NUnit.DataDriven;
    using Ocaramba.Tests.PageObjects.PageObjects.TheInternet;

    [TestFixture]
    [Parallelizable(ParallelScope.Fixtures)]
    public class HerokuappTestsNUnit : ProjectTestBase
    {
        [Test]
        [TestCaseSource(typeof(TestData), "CredentialsExcel")]
        public void FormAuthenticationPageExcelTest(IDictionary<string, string> parameters)
        {
            new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

            var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
            formFormAuthentication.EnterUserName(parameters["user"]);
            formFormAuthentication.EnterPassword(parameters["password"]);
            formFormAuthentication.LogOn();
            Verify.That(
                this.DriverContext,
                () => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));
        }
        
        [Test]
        [TestCaseSource(typeof(TestData), "LinksExcel")]
        public void CountLinksAndSetTestNameAtShiftingContentExcelTest(IDictionary<string, string> parameters)
        {
            new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

            var links = new ShiftingContentPage(this.DriverContext);
            Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
        }

    }
}

Where

[TestCaseSource(typeof(TestData), "CredentialsExcel")]

TestData is a a class for relation between data driven tests and xlsx file from 1.2.2

"CredentialsExcel" is a method from TestData class.

Names of test are set dynamically by the values of test data read from xlsx file e.g:

Only parameters set in diffParam will be used in test case name.

1.2.4 If you want to execute any of your test repeatedly with different test data, just repeat

as many time as you need corresponding row in xlsx file

1.2.5 If you don't need to set test case name use overridden method

        public static IEnumerable LinksExcel
        {
            get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "links"); }
        }

and set test use that method "LinksExcel"

[Test]
[TestCaseSource(typeof(TestData), "LinksExcel")]
public void CountLinksAndSetTestNameAtShiftingContentExcelTest(IDictionary<string, string> parameters)
{
 new InternetPage(this.DriverContext).OpenHomePage().GoToShiftingContentPage();

 var links = new ShiftingContentPage(this.DriverContext);
  Verify.That(this.DriverContext, () => Assert.AreEqual(parameters["number"], links.CountLinks()));
}

Name of test will be set from name of Excel sheet plus row number.

1.2.6 Examples of implementation can be found here:

1.3 Data driven tests from CSV files

Data driven tests from CSV files are not supported with NUnit by default, but you can use DataDrivenHelper class methods from our Test.Automation framework to read CSV files and pass test data to your tests. Test data is passed to the test as parameters (key - name of parameter and key value). Data in first row is used for name of parameters - keys.

1.3.1 Just add CSV file with test data to your NUnit project e.g

Make sure that file properties "Copy to Output Directory" is set to "Copy always" and proper path (relative) is set to that file in TestData.cs file.

     public static IEnumerable CredentialsCSV()
        {
            var path = TestContext.CurrentContext.TestDirectory;
            path = string.Format(CultureInfo.CurrentCulture, "{0}{1}", path, @"\DataDriven\TestDataCsv.csv");
            return DataDrivenHelper.ReadDataDriveFileCsv(path, new[] { "user", "password" }, "credentialCsv");
        }

1.3.2 Create a class for relation between data driven tests and CSV file with test data e.g:

namespace Ocaramba.Tests.NUnit.DataDriven
{
    using System.Collections;

    /// <summary>
    /// DataDriven methods for NUnit test framework
    /// </summary>
    public static class TestData 
    {

        public static IEnumerable CredentialsCSV()
        {
            var path = TestContext.CurrentContext.TestDirectory;
            path = string.Format(CultureInfo.CurrentCulture, "{0}{1}", path, @"\DataDriven\TestDataCsv.csv");
            return DataDrivenHelper.ReadDataDriveFileCsv(path, new[] { "user", "password" }, "credentialCsv");
        }
    }
}

Where calling the method ReadDataDriveFileCsv()

DataDrivenHelper.ReadDataDriveFileCsv(path, new[] { "user", "password" }, "credentialCsv");

from its definitions:

 public static IEnumerable<TestCaseData> ReadDataDriveFileCsv(string file, string[] diffParam, string testName)

file - Full path to Excel DataDriveFile file

diffParam - Values of listed parameters will be used in test case name.

testName - Name of the test, use as prefix for test case name.

Definition of class DataDrivenHelper can be found here

1.3.3 Set tests to use test data from CSV file e.g:

namespace Ocaramba.Tests.NUnit.Tests
{
    using System.Collections.Generic;

    using global::NUnit.Framework;

    using Ocaramba;
    using Ocaramba.Tests.NUnit.DataDriven;
    using Ocaramba.Tests.PageObjects.PageObjects.TheInternet;

    [TestFixture]
    [Parallelizable(ParallelScope.Fixtures)]
    public class HerokuappTestsNUnit : ProjectTestBase
    {
        [Test]
        [TestCaseSource(typeof(TestData), "CredentialsCSV")]
        public void CSVTest(IDictionary<string, string> parameters)
        {
            new InternetPage(this.DriverContext).OpenHomePage().GoToFormAuthenticationPage();

            var formFormAuthentication = new FormAuthenticationPage(this.DriverContext);
            formFormAuthentication.EnterUserName(parameters["user"]);
            formFormAuthentication.EnterPassword(parameters["password"]);
            formFormAuthentication.LogOn();
            Verify.That(
                this.DriverContext,
                () => Assert.AreEqual(parameters["message"], formFormAuthentication.GetMessage));
        }
        
     }

Where

[TestCaseSource(typeof(TestData), "CredentialsCSV")]

TestData is a a class for relation between data driven tests and xlsx file from 1.3.2

"CredentialsCSV" is a method from TestData class.

Names of test are set dynamically by the values of test data read from CSV file and testName property (testName + diffParam) e.g: creadentialCsv_test111_test222

1.3.4 If you want to execute any of your test repeatedly with different test data, just repeat

as many time as you need corresponding row in CSV file

1.3.5 Examples of implementation can be found here:

Clone this wiki locally
You can’t perform that action at this time.