Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Created September 7, 2022 10:42
Show Gist options
  • Save wi7a1ian/e259173fefe8fd329ec87c6c25bd6311 to your computer and use it in GitHub Desktop.
Save wi7a1ian/e259173fefe8fd329ec87c6c25bd6311 to your computer and use it in GitHub Desktop.
Useful classes for data-driven tests in #csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FooBar
{
public class FooBar : Attribute, ITestDataSource
{
private readonly string[] _columnNames;
private readonly string _filePath;
private readonly string _tableName;
public MsTestXmlFileDataAttribute(string filePath, string tableName, params string[] columnNames)
{
_filePath = filePath;
_tableName = tableName;
_columnNames = columnNames;
}
public IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return TestsUtils.GetData(_filePath, _tableName, _columnNames);
}
public string GetDisplayName(MethodInfo methodInfo, object[] data)
{
return data != null
? string.Format(CultureInfo.CurrentCulture, "XmlData - {0} ({1})", methodInfo.Name,
string.Join(",", data))
: null;
}
}
}
[Theory]
[XUnitJsonFileData("TestData/Some.json", typeof(SomeTestData))]
public void ShouldDoSth(SomeTestData data) {}
[TestMethod]
[DeploymentItem("TestData/Some.xml")]
[MsTestXmlFileData("Some.xml", "DataSet", "In1", "In2", "In3", "ExpectedOutput")]
public void ShouldDoSth(string in1, string in2, string in3, string output) {}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using Xunit.Sdk;
namespace FooBar
{
public class XUnitJsonFileDataAttribute : DataAttribute
{
private readonly object[][] deserializedData;
public XUnitJsonFileDataAttribute(string filePath, Type type)
{
var data = File.ReadAllText(filePath);
deserializedData = ((object[])JsonSerializer.Deserialize(data, type.MakeArrayType()))
.Select(f => new[] { f })
.ToArray();
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return deserializedData;
}
}
}
using System.Collections.Generic;
using System.Reflection;
using Xunit.Sdk;
namespace FooBar
{
public class XUnitXmlFileDataAttribute : DataAttribute
{
private readonly string[] _columnNames;
private readonly string _filePath;
private readonly string _tableName;
public XUnitXmlFileDataAttribute(string filePath, string tableName, params string[] columnNames)
{
_filePath = filePath;
_tableName = tableName;
_columnNames = columnNames;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return TestsUtils.GetData(_filePath, _tableName, _columnNames);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment