xUnit parameterized test with file data
2 min read
In xUnit parameterized tests are called theories. Test data is passed to a theory using subclasses of DataAttribute
.
For this example I created a text file, TextFile1.txt
, in my test projects’ root dir and set its Copy to Output Directory property to Copy always.
I created a test class, with a method taking one string
parameter. I decorated the method with [Theory, FileData("TextFile1.txt")]
and added this class:
namespace Logikfabrik.Xunit
{
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using global::Xunit.Sdk;
public class FileDataAttribute : DataAttribute
{
private readonly string _path;
public FileDataAttribute(string path)
{
_path = path;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
if (File.Exists(_path))
{
yield return new object[] { File.ReadAllText(_path) };
}
else if (Directory.Exists(_path))
{
foreach (var path in Directory.EnumerateFiles(_path, "*.*", SearchOption.AllDirectories))
{
yield return new object[] { File.ReadAllText(path) };
}
}
}
}
}
xUnit discovers the attribute, reads the file, and passes the data to the theory.