Best Ocaramba code snippet using Ocaramba.Tests.NUnit.DataDriven.DataDrivenHelper.TestCaseName
DataDrivenHelper.cs
Source:DataDrivenHelper.cs  
...70                var testParams = element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value);71                var testCaseName = string.IsNullOrEmpty(testName) ? testData : testName;72                try73                {74                    testCaseName = TestCaseName(diffParam, testParams, testCaseName);75                }76                catch (DataDrivenReadException e)77                {78                    throw new DataDrivenReadException(79                        string.Format(80                            " Exception while reading Data Driven file\n test data '{0}' \n test name '{1}' \n searched key '{2}' not found in row \n '{3}'  \n in file '{4}'",81                            testData,82                            testName,83                            e.Message,84                            element,85                            folder));86                }87                var data = new TestCaseData(testParams);88                data.SetName(testCaseName);89                yield return data;90            }91        }92        /// <summary>93        /// Reads the Csv data drive file and set test name.94        /// </summary>95        /// <param name="file">Full path to csv DataDriveFile file.</param>96        /// <param name="diffParam">The difference parameter.</param>97        /// <param name="testName">Name of the test, use as prefix for test case name.</param>98        /// <returns>99        /// IEnumerable TestCaseData.100        /// </returns>101        /// <exception cref="InvalidOperationException">Exception when wrong cell type in file.</exception>102        /// <exception cref="DataDrivenReadException">Exception when parameter not found in row.</exception>103        /// <example>How to use it: <code>104        ///  {105        ///  var path = TestContext.CurrentContext.TestDirectory;106        ///  path = string.Format(CultureInfo.CurrentCulture, "{0}{1}", path, @"\DataDriven\TestDataCsv.csv");107        ///  return DataDrivenHelper.ReadDataDriveFileCsv(path, new[] { "user", "password" }, "credentialCsv");108        ///  }109        /// </code></example>110        public static IEnumerable<TestCaseData> ReadDataDriveFileCsv(string file, string[] diffParam, string testName)111        {112            using (var fs = File.OpenRead(file))113            using (var sr = new StreamReader(fs))114            {115                string line = string.Empty;116                line = sr.ReadLine();117                string[] columns = line.Split(118                                new char[] { ';' },119                                StringSplitOptions.None);120                var columnsNumber = columns.Length;121                var row = 1;122                while (line != null)123                {124                    string testCaseName;125                    line = sr.ReadLine();126                    if (line != null)127                    {128                        var testParams = new Dictionary<string, string>();129                        string[] split = line.Split(130                            new char[] { ';' },131                            StringSplitOptions.None);132                        for (int i = 0; i < columnsNumber; i++)133                        {134                            testParams.Add(columns[i], split[i]);135                        }136                        try137                        {138                            testCaseName = TestCaseName(diffParam, testParams, testName);139                        }140                        catch (DataDrivenReadException e)141                        {142                            throw new DataDrivenReadException(143                            string.Format(144                                " Exception while reading Csv Data Driven file\n searched key '{0}' not found \n for test {1} in file '{2}' at row {3}",145                                e.Message,146                                testName,147                                file,148                                row));149                        }150                        row += 1;151                        var data = new TestCaseData(testParams);152                        data.SetName(testCaseName);153                        yield return data;154                    }155                }156            }157        }158        /// <summary>159        /// Reads the data drive file without setting test name.160        /// </summary>161        /// <param name="folder">Full path to XML DataDriveFile file.</param>162        /// <param name="testData">Name of the child element in xml file.</param>163        /// <returns>164        /// IEnumerable TestCaseData.165        /// </returns>166        /// <exception cref="ArgumentNullException">Exception when element not found in file.</exception>167        /// <example>How to use it: <code>168        /// public static IEnumerable Credentials169        /// {170        /// get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential"); }171        /// }172        /// </code></example>173        public static IEnumerable<TestCaseData> ReadDataDriveFile(string folder, string testData)174        {175            var doc = XDocument.Load(folder);176            if (!doc.Descendants(testData).Any())177            {178                throw new ArgumentNullException(string.Format(CultureInfo.CurrentCulture, "Exception while reading Data Driven file\n row '{0}' not found \n in file '{1}'", testData, folder));179            }180            return doc.Descendants(testData).Select(element => element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value)).Select(testParams => new TestCaseData(testParams));181        }182        /// <summary>183        /// Reads the Excel data drive file and optionaly set test name.184        /// </summary>185        /// <param name="path">Full path to Excel DataDriveFile file.</param>186        /// <param name="sheetName">Name of the sheet at xlsx file.</param>187        /// <param name="diffParam">Optional values of listed parameters will be used in test case name.</param>188        /// <param name="testName">Optional name of the test, use as prefix for test case name.</param>189        /// <returns>190        /// IEnumerable TestCaseData.191        /// </returns>192        /// <exception cref="InvalidOperationException">Exception when wrong cell type in file.</exception>193        /// <exception cref="DataDrivenReadException">Exception when parameter not found in row.</exception>194        /// <example>How to use it: <code>195        /// public static IEnumerable CredentialsFromExcel196        /// {197        /// get { return DataDrivenHelper.ReadXlsxDataDriveFile(ProjectBaseConfiguration.DataDrivenFileXlsx, "credential", new[] { "user", "password" }, "credentialExcel"); }198        /// }199        /// </code></example>200        public static IEnumerable<TestCaseData> ReadXlsxDataDriveFile(string path, string sheetName, [Optional] string[] diffParam, [Optional] string testName)201        {202            Logger.Debug("Sheet {0} in file: {1}", sheetName, path);203            XSSFWorkbook wb;204            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))205            {206                wb = new XSSFWorkbook(fs);207            }208            // get sheet209            var sh = (XSSFSheet)wb.GetSheet(sheetName);210            int startRow = 1;211            int startCol = 0;212            int totalRows = sh.LastRowNum;213            int totalCols = sh.GetRow(0).LastCellNum;214            var row = 1;215            for (int i = startRow; i <= totalRows; i++, row++)216            {217                var column = 0;218                var testParams = new Dictionary<string, string>();219                for (int j = startCol; j < totalCols; j++, column++)220                {221                    if (sh.GetRow(0).GetCell(column).CellType != CellType.String)222                    {223                        throw new InvalidOperationException(string.Format("Cell with name of parameter must be string only, file {0} at sheet {1} row {2} column {3}", path, sheetName, 0, column));224                    }225                    var cellType = sh.GetRow(row).GetCell(column).CellType;226                    switch (cellType)227                    {228                        case CellType.String:229                            testParams.Add(sh.GetRow(0).GetCell(column).StringCellValue, sh.GetRow(row).GetCell(column).StringCellValue);230                            break;231                        case CellType.Numeric:232                            testParams.Add(sh.GetRow(0).GetCell(column).StringCellValue, sh.GetRow(row).GetCell(column).NumericCellValue.ToString(CultureInfo.CurrentCulture));233                            break;234                        default:235                            throw new InvalidOperationException(string.Format("Not supported cell type {0} in file {1} at sheet {2} row {3} column {4}", cellType, path, sheetName, row, column));236                    }237                }238                // set test name239                var testCaseName = string.IsNullOrEmpty(testName) ? sheetName : testName;240                if (diffParam != null && diffParam.Any())241                {242                    try243                    {244                        testCaseName = TestCaseName(diffParam, testParams, testCaseName);245                    }246                    catch (DataDrivenReadException e)247                    {248                        throw new DataDrivenReadException(249                            string.Format(250                                " Exception while reading Excel Data Driven file\n searched key '{0}' not found at sheet '{1}' \n for test {2} in file '{3}' at row {4}",251                                e.Message,252                                sheetName,253                                testName,254                                path,255                                row));256                    }257                }258                else259                {260                    testCaseName = testCaseName + "_row(" + row + ")";261                }262                var data = new TestCaseData(testParams);263                data.SetName(testCaseName);264                yield return data;265            }266        }267        /// <summary>268        /// Get the name of test case from value of parameters.269        /// </summary>270        /// <param name="diffParam">The difference parameter.</param>271        /// <param name="testParams">The test parameters.</param>272        /// <param name="testCaseName">Name of the test case.</param>273        /// <returns>Test case name.</returns>274        /// <exception cref="NullReferenceException">Exception when trying to set test case name.</exception>275        private static string TestCaseName(string[] diffParam, Dictionary<string, string> testParams, string testCaseName)276        {277            if (diffParam != null && diffParam.Any())278            {279                foreach (var p in diffParam)280                {281                    bool keyFlag = testParams.TryGetValue(p, out string keyValue);282                    if (keyFlag)283                    {284                        if (!string.IsNullOrEmpty(keyValue))285                        {286                            testCaseName += "_" + Regex.Replace(keyValue, "[^0-9a-zA-Z]+", "_");287                        }288                    }289                    else...TestCaseName
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Ocaramba.Tests.NUnit.DataDriven;7using NUnit.Framework;8{9    {10        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]11        public void TestCaseNameTest(string testCaseName)12        {13            Assert.IsNotNull(testCaseName);14        }15    }16}TestCaseName
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Ocaramba;7using Ocaramba.Tests.NUnit.DataDriven;8using NUnit.Framework;9using NUnit.Framework.Interfaces;10using System.IO;11{12    [TestFixtureSource("TestCaseName")]13    {14        private string name;15        private string surname;16        private string age;17        public DataDrivenTest(string name, string surname, string age)18        {19            this.name = name;20            this.surname = surname;21            this.age = age;22        }23        public void DataDrivenTest1()24        {25            Console.WriteLine("Name: " + name);26            Console.WriteLine("Surname: " + surname);27            Console.WriteLine("Age: " + age);28        }29        public static string[] TestCaseName()30        {31            string[] lines = File.ReadAllLines("C:\\Users\\user\\Desktop\\test.txt");32            return lines;33        }34    }35}TestCaseName
Using AI Code Generation
1using Ocaramba.Tests.NUnit.DataDriven;2using NUnit.Framework;3{4    [Category("DataDriven")]5    {6        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]7        public void DataDrivenTest(string name)8        {9            Assert.AreEqual("Test", name);10        }11    }12}13using System;14using System.Collections;15using System.Collections.Generic;16using System.Linq;17using System.Text;18using System.Threading.Tasks;19{20    {21        {22            {23                yield return new TestCaseData("Test").SetName("DataDrivenTest");24            }25        }26    }27}28using NUnit.Framework;29using Ocaramba;30using Ocaramba.Types;31using System;32using System.Collections.Generic;33using System.Linq;34using System.Text;35using System.Threading.Tasks;36{37    {38        public ProjectTestBase(DriverContext driverContext)39            : base(driverContext)40        {41        }42        public ProjectTestBase()43            : base(DriverContext.ExtentReports)44        {45        }46    }47}48using System;49using System.Collections.Generic;50using System.Linq;51using System.Text;52using System.Threading.Tasks;53using NUnit.Framework;54using Ocaramba;55using Ocaramba.Types;56{57    {58        public TestBase(DriverContext driverContext)59            : base(driverContext)60        {61        }62        public TestBase()63            : base(DriverContext.ExtentReports)64        {65        }66    }67}68using System;69using System.Collections.Generic;70using System.Linq;71using System.Text;72using System.Threading.Tasks;73using AventStack.ExtentReports;74using AventStack.ExtentReports.Reporter;75using NUnit.Framework;76using Ocaramba;77using Ocaramba.Types;78{79    {80        public BaseTest(DriverContext driverContext)81            : base(driverContext)82        {83        }TestCaseName
Using AI Code Generation
1using Ocaramba.Tests.NUnit.DataDriven;2using NUnit.Framework;3{4    [Category("DataDriven")]5    {6        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]7        public void DataDrivenTest1(string testCaseName)8        {9            Assert.IsTrue(true);10        }11    }12}13using Ocaramba.Tests.NUnit.DataDriven;14using NUnit.Framework;15{16    [Category("DataDriven")]17    {18        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]19        public void DataDrivenTest1(string testCaseName)20        {21            Assert.IsTrue(true);22        }23    }24}25using Ocaramba.Tests.NUnit.DataDriven;26using NUnit.Framework;27{28    [Category("DataDriven")]29    {30        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]31        public void DataDrivenTest1(string testCaseName)32        {33            Assert.IsTrue(true);34        }35    }36}37using Ocaramba.Tests.NUnit.DataDriven;38using NUnit.Framework;39{40    [Category("DataDriven")]41    {42        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]43        public void DataDrivenTest1(string testCaseName)44        {45            Assert.IsTrue(true);46        }47    }48}TestCaseName
Using AI Code Generation
1[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]2public void TestMethod1(string name, int age)3{4}5[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]6public void TestMethod1(string name, int age)7{8}9[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]10public void TestMethod1(string name, int age)11{12}13[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]14public void TestMethod1(string name, int age)15{16}17[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]18public void TestMethod1(string name, int age)19{20}21[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]22public void TestMethod1(string name, int age)23{24}25[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]26public void TestMethod1(string name, int age)27{28}29[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]30public void TestMethod1(string name, int age)31{32}33[TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]34public void TestMethod1(string name, int age)35{36}TestCaseName
Using AI Code Generation
1using NUnit.Framework;2using Ocaramba.Tests.NUnit.DataDriven;3{4    {5        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]6        public void DataDrivenTest1(string testCaseName)7        {8            Assert.AreEqual("test1", testCaseName);9        }10    }11}12using NUnit.Framework;13using Ocaramba.Tests.NUnit.DataDriven;14{15    {16        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]17        public void DataDrivenTest1(string testCaseName)18        {19            Assert.AreEqual("test2", testCaseName);20        }21    }22}23using NUnit.Framework;24using Ocaramba.Tests.NUnit.DataDriven;25{26    {27        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]28        public void DataDrivenTest1(string testCaseName)29        {30            Assert.AreEqual("test3", testCaseName);31        }32    }33}34using NUnit.Framework;35using Ocaramba.Tests.NUnit.DataDriven;36{37    {38        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]39        public void DataDrivenTest1(string testCaseName)40        {41            Assert.AreEqual("test4", testCaseName);42        }43    }44}45using NUnit.Framework;46using Ocaramba.Tests.NUnit.DataDriven;47{TestCaseName
Using AI Code Generation
1using Ocaramba.Tests.NUnit.DataDriven;2using NUnit.Framework;3using System.IO;4using System.Reflection;5{6    {7        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]8        public void DataDrivenTest1(string testCaseName)9        {10            string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);11            string filePath = Path.Combine(currentDir, "TestData.xlsx");12            string testData = DataDrivenHelper.GetDataFromExcel(testCaseName, filePath, "Sheet1");13            System.Console.WriteLine(testData);14        }15    }16}17using Ocaramba.Tests.NUnit.DataDriven;18using NUnit.Framework;19using System.IO;20using System.Reflection;21{22    {23        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]24        public void DataDrivenTest1(string testCaseName)25        {26            string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);27            string filePath = Path.Combine(currentDir, "TestData.xml");28            string testData = DataDrivenHelper.GetDataFromXML(testCaseName, filePath, "Data");29            System.Console.WriteLine(testData);30        }31    }32}33using Ocaramba.Tests.NUnit.DataDriven;34using NUnit.Framework;35using System.IO;36using System.Reflection;37{38    {39        [TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]40        public void DataDrivenTest1(string testCaseName)41        {42            string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);43            string filePath = Path.Combine(currentDir, "TestData.json");TestCaseName
Using AI Code Generation
1{2    [Test, TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]3    public void TestMethod(string parameter1, string parameter2)4    {5    }6}7{8    [Test, TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]9    public void TestMethod(string parameter1, string parameter2, string parameter3)10    {11    }12}13{14    [Test, TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]15    public void TestMethod(string parameter1, string parameter2, string parameter3, string parameter4)16    {17    }18}19{20    [Test, TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]21    public void TestMethod(string parameter1, string parameter2, string parameter3, string parameter4, string parameter5)22    {23    }24}25{26    [Test, TestCaseSource(typeof(DataDrivenHelper), "TestCaseName")]27    public void TestMethod(string parameter1, string parameter2, string parameter3, string parameter4, string parameter5, string parameter6)28    {29    }30}TestCaseName
Using AI Code Generation
1using System;2using System.IO;3using System.Reflection;4using System.Xml;5using NUnit.Framework;6using Ocaramba;7using Ocaramba.Tests.NUnit.DataDriven;8{9    {10        [TestCaseSource("GetXmlData", new object[] { "2.xml" })]11        public void TestMethod1(string name)12        {13            Console.WriteLine(name);14        }15        [TestCaseSource("GetXmlData", new object[] { "3.xml" })]16        public void TestMethod2(string name)17        {18            Console.WriteLine(name);19        }20        [TestCaseSource("GetXmlData", new object[] { "4.xml" })]21        public void TestMethod3(string name)22        {23            Console.WriteLine(name);24        }25        [TestCaseSource("GetXmlData", new object[] { "5.xml" })]26        public void TestMethod4(string name)27        {28            Console.WriteLine(name);29        }30        [TestCaseSource("GetXmlData", new object[] { "6.xml" })]31        public void TestMethod5(string name)32        {33            Console.WriteLine(name);34        }35        [TestCaseSource("GetXmlData", new object[] { "7.xml" })]36        public void TestMethod6(string name)37        {38            Console.WriteLine(name);39        }40        [TestCaseSource("GetXmlData", new object[] { "8.xml" })]41        public void TestMethod7(string name)42        {43            Console.WriteLine(name);44        }45        [TestCaseSource("GetXmlData", new object[] { "9.xml" })]46        public void TestMethod8(string name)47        {48            Console.WriteLine(name);49        }50        public static string GetXmlData(string fileName)51        {52            var xmlDocument = new XmlDocument();53            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);54            xmlDocument.Load(path);55            var nodeList = xmlDocument.SelectNodes("/ArrayOfString/String");56            return DataDrivenHelper.TestCaseName(nodeList);57        }58    }59}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
