1

I wanted to write unit tests for all files in specific path. For example - first run will be for file x, second for file y, etc.

But I have problem with converting IEnumerable<string> to IEnumerable<object[]>:

public static IEnumerable<object[]> ExpectedOutputFiles;

public JsonParserTests()
{
    var files = Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GetOutputDataFolder()));
    ExpectedOutputFiles = files; // <--- Error is here
}

[Theory]
[MemberData(nameof(ExpectedOutputFiles))]
public void OutputFile_ShouldBeParsedCorrectlyAsJSON_RFC8259(string filename)
{
    // Test parsing output files with Newtonsoft.Json and System.Text.Json
    var json = File.ReadAllText(filename);
    JToken.Parse(json);
    // System.Text.Json have better default options compatible with RFC 8259 specification
    JsonDocument.Parse(json);
}

Is this possible, or should I create [Fact] unit test and read files in foreach loop?

Saibamen
  • 610
  • 3
  • 17
  • 43
  • 1
    The problem is simply that `ExpectedOutputFiles` is an `IEnumerable`, and `files` is an `IEnumerable`. xUnit wants an `IEnumerable` where each element in the `IEnumerable` is an array of objects, containing all of the parameters to pass to your test method. Your test method has 1 parameter, so each element should be a 1-element object array. I.e. you want `ExpectedOutputFiles = files.Select(x => new object[] { x })` – canton7 Jun 21 '21 at 14:23

1 Answers1

1

Move the code from the constructor to the static member

public static IEnumerable<object[]> ExpectedOutputFiles() {
    var files = Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GetOutputDataFolder()));
    foreach(var file in files) {
        yield return new object[] { file };
    }
}

//...

and return each file in an object array

Reference xUnit Theory: Working With InlineData, MemberData, ClassData

Nkosi
  • 235,767
  • 35
  • 427
  • 472