Last active
March 24, 2017 12:13
-
-
Save stiano/cdb8899ed715925f5dd50955ab75e73e to your computer and use it in GitHub Desktop.
Simple way of generating test data in an Excel file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dependencies: NUnit | |
// Remember: copy excel file to output directory | |
public class ExcelBasedTests | |
{ | |
[Test, TestCaseSource(typeof(TestData), nameof(TestData.GetPeriodStartDateCases))] | |
public void RegisterUserTest(PeriodStartDateModel input) | |
{ | |
input.ColumnA.ShouldNotBeNullOrEmpty(); | |
input.ColumnB.ShouldNotBeNullOrEmpty(); | |
input.ColumnC.ShouldNotBeNullOrEmpty(); | |
} | |
} | |
public class PeriodStartDateModel | |
{ | |
public string ColumnA { get; set; } | |
public string ColumnB { get; set; } | |
public string ColumnC { get; set; } | |
} | |
public class TestData | |
{ | |
public static IEnumerable<TestCaseData> GetPeriodStartDateCases() | |
{ | |
var relativeFilename = Path.Combine("Util", "period-start-date.xlsx"); | |
return BuildTestCases(relativeFilename, row => | |
{ | |
var model = new PeriodStartDateModel(); | |
model.ColumnA = row["A"].ToString(); | |
model.ColumnB = row["B"].ToString(); | |
model.ColumnC = row["C"].ToString(); | |
return model; | |
}); | |
} | |
private static IEnumerable<TestCaseData> BuildTestCases(string relativeFilename, Func<DataRow, object> mapper) | |
{ | |
var path = Path.Combine(TestContext.CurrentContext.TestDirectory, relativeFilename); | |
var isBinaryFormat = path | |
.ToLower() | |
.EndsWith("xls"); | |
using (var fileStream = File.OpenRead(path)) | |
{ | |
var excelDataReader = isBinaryFormat | |
? ExcelReaderFactory.CreateBinaryReader(fileStream) | |
: ExcelReaderFactory.CreateOpenXmlReader(fileStream); | |
using (excelDataReader) | |
{ | |
excelDataReader.IsFirstRowAsColumnNames = true; | |
var dataset = excelDataReader.AsDataSet(); | |
foreach (DataRow row in dataset.Tables[0].Rows) | |
{ | |
var testCase = mapper(row); | |
yield return new TestCaseData(new[] { testCase }); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment