Последовательное чтение данных из Excel в тестовых случаях C # / NUnit возвращает пустые данные для второго варианта - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь написать параметризованный тест NUnit, который выполняется дважды. Каждый раз, когда он запускается, он ссылается на другую строку в электронной таблице и получает имя пользователя и пароль на основе int rowNum .

    class Test
    {
        //Run the test twice
        [Test,TestCase(1),TestCase(2)]
        public void T101_LoginTestSuite_Valid(int rowNum)
        {
            Console.WriteLine(TestContext.CurrentContext.Test.MethodName); //Test Name 
            Console.WriteLine("Row number "+rowNum);// Value of rowNum

            ExcelDataFactory.GetTestDataSet(TestContext.CurrentContext.Test.MethodName);

            //Print out the credentials
            Console.WriteLine(ExcelDataFactory.ReadData(rowNum,"username")); 
            Console.WriteLine(ExcelDataFactory.ReadData(rowNum, "password"));
        }
    }

Вот превосходство

excel spreadsheet

Первый тестовый пример правильно получает имя пользователя и пароль.

test1

Однако второй тестовый случай возвращается пустым (если я запускаю это по отдельности, он будет работать!)

test2

Ниже ExcelDataFactory code:

    class ExcelDataFactory
    {
        //Get data from excel
        private static DataTable ExcelToDataTable(String filename, String sheetName)
        {
            //Open file and returns as Stream
            FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);

            //CreateOpenXmlReader via ExcelReaderFactory 
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx

            //Return as DataSet and set the frist row as column name
            DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });

            DataTableCollection table = result.Tables;


            DataTable resultTable = table[sheetName];

            //Close FileStream
            stream.Close();

            //Return
            return resultTable; 
        }

        //Put data into a collection 
        static List<DataCollection> dataCollection = new List<DataCollection>();

        public static void PopulateInCollection(string fileName, String sheetName)
        {
            DataTable table = ExcelToDataTable(fileName,sheetName);

            //Iterate through the rows and columns of the Table
            for(int row = 1; row <= table.Rows.Count; row++)
            {
                for (int column = 0; column < table.Columns.Count; column++)
                {
                    DataCollection dataTable = new DataCollection()
                    {
                        rowNumber = row,
                        columnName = table.Columns[column].ColumnName,
                        columnValue = table.Rows[row - 1][column].ToString()
                    };
                    //Add all the details for each row
                    dataCollection.Add(dataTable);
                }
            }
        }

        //Find the correct excel file and sheet
        public static void GetTestDataSet(String testName)
        {
            String[] testNameSplit = testName.Split('_');
            String filePath = MyProps.Default.TestData //Add path
                    + testNameSplit[1]
                    + "."
                    + "xlsx";
            PopulateInCollection(filePath, testNameSplit[0]);
        }

        public static string ReadData(int rowNumber, string columnName)
        {
            try 
            {
                //Retriving Data using LINQ to reduce amount of iterations
                string data = (from collectionData in dataCollection
                               where collectionData.columnName == columnName && collectionData.rowNumber == rowNumber
                               select collectionData.columnValue).SingleOrDefault();

                //var data   = dataCollection.Where(collectionData => collectionData.columnName == columnName && collectionData.rowNumber == rowNumber).SingleOrDefault().columnValue; 
                return data.ToString();
            } 
            catch (Exception e)
            {
                e.StackTrace.ToString();
                return null;
            }
        }

    }  

    class DataCollection
    {
        public int rowNumber { get; set; }

        public string columnName { get; set; }

        public string columnValue { get; set; }
    }

Я подозреваю, что метод ExcelDataFactory.GetTestDataSet вызван не в том месте, но я действительно озадачен тем, почему это происходит. Любые идеи очень приветствуются.

1 Ответ

0 голосов
/ 17 апреля 2020

Я сделал несколько быстрых изменений в классе ExcelDataFactory , удалил ссылки stati c и теперь метод PopulateInCollection возвращает Список который объявлен и инициализирован в начале класса.

using ExcelDataReader;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wizuda_Selenium_Test_Automation
{
    class ExcelDataFactory
    {
        List<DataCollection> dataCollection = new List<DataCollection>();

        private static DataTable ExcelToDataTable(String filename, String sheetName)
        {
            //Open file and returns as Stream
            FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);

            //CreateOpenXmlReader via ExcelReaderFactory 
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx

            //Return as DataSet and set the frist row as column name
            DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });

            DataTableCollection table = result.Tables;


            DataTable resultTable = table[sheetName];

            //Close FileStream
            stream.Close();

            //Return
            return resultTable; 
        }

        //static List<DataCollection> dataCollection = new List<DataCollection>();

        public List<DataCollection> PopulateInCollection(string fileName, String sheetName)
        {
            dataCollection = new List<DataCollection>();

            DataTable table = ExcelToDataTable(fileName,sheetName);

            //Iterate through the rows and columns of the Table
            for(int row = 1; row <= table.Rows.Count; row++)
            {
                for (int column = 0; column < table.Columns.Count; column++)
                {
                    DataCollection dataTable = new DataCollection()
                    {
                        rowNumber = row,
                        columnName = table.Columns[column].ColumnName,
                        columnValue = table.Rows[row - 1][column].ToString()
                    };

                    //Add all the details for each row
                    dataCollection.Add(dataTable);
                }
            }

            return dataCollection;
        }

        public string ReadData(int rowNumber, string columnName)
        {
            try 
            {
                //Retriving Data using LINQ to reduce amount of iterations
                string data = (from collectionData in dataCollection
                               where collectionData.columnName == columnName && collectionData.rowNumber == rowNumber
                               select collectionData.columnValue).SingleOrDefault();

                //var data   = dataCollection.Where(collectionData => collectionData.columnName == columnName && collectionData.rowNumber == rowNumber).SingleOrDefault().columnValue; 
                return data.ToString();
            } 
            catch (Exception e)
            {
                e.StackTrace.ToString();
                return null;
            }
        }

        public void GetTestDataSet(String testName)
        {
            String[] testNameSplit = testName.Split('_');
            String filePath = MyProps.Default.TestData //Add path
                    + testNameSplit[1] //LoginTestSuite
                    + "."
                    + "xlsx";              //T101
            PopulateInCollection(filePath, testNameSplit[0]);
        }
    }  

    class DataCollection
    {
        public int rowNumber { get; set; }

        public string columnName { get; set; }

        public string columnValue { get; set; }
    }
}

Я обновил тест, чтобы создать новый экземпляр ExcelDataFactory

        [Test,TestCase(1),TestCase(2)]
        public void T101_LoginTestSuite_Valid(int rowNum)
        {
            ExcelDataFactory excelDataFactory = new ExcelDataFactory();

            Console.WriteLine(TestContext.CurrentContext.Test.MethodName);
            Console.WriteLine("Row number "+rowNum);
            excelDataFactory.GetTestDataSet(TestContext.CurrentContext.Test.MethodName);

            Console.WriteLine("username= "+ excelDataFactory.ReadData(rowNum,"username"));
            Console.WriteLine("password= "+ excelDataFactory.ReadData(rowNum, "password"));
        }

А теперь тесты пройдены

test1 test2

Полагаю, мне нужно go вернуться назад и заново узнать о состоянии использования c методов, спасибо Kritner

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...