Ranorex Blog - Software Automation & Automated Testing Blog

Posted by cpreschern on Wednesday, July 23rd, 2008 at 10:08 am to Test Automation

Data driven test automation with Excel

Download Ranorex

Download Ranorex Studio Excel Sample for Ranorex 2.0 (15KB)

Microsoft Excel is often used to store and manage test cases and test data. Why? Because Excel is a widespread tool. Nearly every Windows based machine has installed Microsoft Office.
Following example describes how to feed a Ranorex test automation process with test data stored within an Excel table. The example consists of 3 main parts:

  • Excel sheet containing test data
  • Ranorex automation project
  • Excel connector to read test data from Excel

Data driven testing with Excel

Excel Sheet

As usual, we use the Windows calculator in this example of data driven testing. Each row defines a single test case with test data inputs and expected outputs. In addition, each test case has a short description.

ExcelConnector class

To provide a user-friendly interface for retrieving test data from an Excel sheet, we implement an ExcelConnector. This class wraps the functionality of a Microsoft COM library to access rows and cells in a data sheet. Thus we have to add the COM library as reference object to our project.

Add Excel Reference

public class ExcelConnector
{
    private string excelFile = null;
    private Excel.Application excelObj = null;
    private Excel.Workbook workBook = null;
    private Excel.Worksheet worksheet = null;
    private UInt16 currentRowIndex = 0;
    private string[] inputs;
    private string[] outputs;

    public string ExcelFile
    {
        get
        {
            return this.excelFile;
        }
    }
    public UInt16 CurrentRowIndex
    {
        get
        {
            return this.currentRowIndex;
        }
    }       

    public ExcelConnector(string excelFile, string[] inputs, string[] outputs, bool load, UInt16 startRow)
    {
        this.excelFile = excelFile;
        this.inputs = inputs;
        this.outputs = outputs;
        if (load)
           this.LoadFile();
        currentRowIndex = startRow;
    }

    public void LoadFile()
    {
        excelObj = new Excel.Application();
        System.Threading.Thread.CurrentThread.CurrentCulture = new
                                             System.Globalization.CultureInfo("en-US");
        workBook = excelObj.Workbooks.Open(this.excelFile, 0, true, 5, "", "", true,
                                             Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);
        Excel.Sheets sheets = workBook.Worksheets;
        worksheet = (Excel.Worksheet)sheets.get_Item(1);
    }

    public TestData GetNext()
    {
        string[] arrInputs = new string[inputs.Length];
        string[] arrOutputs = new string[outputs.Length];

        for (int i = 1; i < this.inputs.Length+1; i++)
        {
            Excel.Range cell = (Excel.Range)worksheet.Cells[currentRowIndex, i];
            if ( ((string)cell.Text).Length == 0 )
            	return null;
            arrInputs[i - 1] = (string)cell.Text;
        }
        for (int i = 0; i < this.outputs.Length ; i++)
        {
            Excel.Range cell = (Excel.Range)worksheet.Cells[currentRowIndex, i + inputs.Length + 1];
            if ( ((string)cell.Text).Length == 0 )
             	return null;
            arrOutputs[i] = (string)cell.Text;
        }

        Excel.Range cellComment = (Excel.Range)worksheet.Cells[currentRowIndex,
                                                        inputs.Length+outputs.Length+1];
        currentRowIndex++;
        return new TestData(arrInputs, arrOutputs, (string)cellComment.Text);
    }

    public void Dispose()
    {
        excelObj.Quit();
    }
}

The constructor of the class ‘ExcelConnector’ specifies the name of the Excel file, the amount of in- and outputs defined by each test case and where to start reading test data. The ‘GetNext()’ method returns a simple TestData object representing a single row from the excel sheet.

Ranorex test automation code

The following code shows how to use the ‘ExcelConnector’ class to read test data from the excel sheet.

TestData testData;

openFileDialog.DefaultExt = "xlsx";

openFileDialog.Filter = "XLS file (*.xls)|*.xls|XLSX file (*.xlsx)|*.xlsx|All files (*.*)|*.*";
if ( openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
    this.tbExcelFile.Text = openFileDialog.FileName;
}

void InitExcelConnection()
{
    string[] testDataInputs = new string[] { "Input1", "Input2", "Input3", "Input4" };
    string[] testDataOutputs = new string[] { "Output1" };
    if (System.IO.File.Exists(tbExcelFile.Text))
         excelConnector = new ExcelConnector(this.tbExcelFile.Text,
                                    testDataInputs, testDataOutputs, true,2);
    else
         throw new RanorexException(null,"Specified file does not exist!");
}

InitExcelConnection();

while ((testData = excelConnector.GetNext()) != null )
{
    Ranorex.Control bt = null;
    foreach (string str in testData.Inputs)
    {
        foreach (char c in str)
        {
            bt = calcForm.FindChildText(c.ToString());
            Mouse.ClickControl(bt);
        }
    }
    bt = calcForm.FindControlId(403);
    // Compare calculator output with expected value
    Ranorex.Validate.HasText(bt, testData.Outputs[0] + ", ",testData.Description + " validation",false);
}

An Excel connector could be a smart solution to reuse existing manual tests stored in excel sheets and to provide an easy to use test case data base, especially for those testers without deeper Ranorex test automation knowledge.

Share/Save/Bookmark

10 comments

  1. Gregor

    Thank you, cpreschern. I’m working on my final degree on software testing and was looking for something like this.

  2. Paul Wolber

    I tried running “ExcelTestDataConnector.rxsln” and got the following error message:

    Error loading code-completion information for Excel from Excel:
    Could not find assembly file.

    Any thoughts on why? I am running Excel 2007 under Windows XP.

    Thanks-in-advance!

    -pKw

  3. Paracelsus

    I gave the same error message.

    Error loading code-completion information for Excel from Excel:
    Could not find assembly file.

  4. Paracelsus

    How can I make this code in VB.NET ?

  5. Russ Boivin

    I’m also getting the same error. Has anyone been able to get this to work in VB.NET?

  6. Christoph

    Simply use the convert feature in Ranorex Studio by selecting the context menu item ‘Convert’ | ‘From C# to VB.NET’.

    Please remove and add the required COM library as described above again within the ‘References’ node of the project.

  7. Russ

    I apologize if this is the incorrect location to post my response and will post in the forums section regarding the issues I have and still encounter.

  8. Anfal

    The above code is throwing this error

    System.NullReferenceException: Object reference not set to an instance of an object.
    at ExcelTestDataConnector.MainForm.Test1() in c:\Documents and Settings\anfalm\Desktop\DataDriven_Excel\MainForm.cs:line 101
    at ExcelTestDataConnector.MainForm.BtStartTestClick(Object sender, EventArgs e) in c:\Documents and Settings\anfalm\Desktop\DataDriven_Excel\MainForm.cs:line 79

  9. ahoisl

    The above exception can happen if the Excel file you specify does not exist. Check the Excel file name before starting the test.
    Please, have in mind that the project posted in this blog is really only a sample and should only give you the idea, how to create data-driven test automation with Excel using Ranorex.

  10. Ricardo

    I’m working on my final degree on software testing and i have to create an automated test platform.First of all i am on a research phase and i will evaluate several automated test solutions in the market.At this momento i´m evaluating Ranorex 2.2 and i would like to know if ranorex supports : data grid control validation(INSERT,Update,Delete), application menus validations,roles permissions validation,copy folders,workflows validation and Execution of application scripts (commonly used in Cerberus)?

Leave a Reply