19

In these days I'm trying to understand how xUnit tests work and, in particular, I discovered that there are 3 ways to pass data as parameters in order to test class methods (InlineData, ClassData and MemberData). But here Is my issue: is there any chance to get these data from an external file? (For example a Json file) I wasn't unable to find enough material about this topic, thanks for the attention!

Ruber
  • 342
  • 1
  • 2
  • 12

2 Answers2

26

xUnit has been designed to be extensible, i.a. via the DataAttribute.

InlineData, ClassData and MemberData all derive from DataAttribute, which you can extend yourself to create a custom data source for a data theory, in which you may read from you external file and use e.g. Json.NET to deserialize your data.

User Sock wrote about this in his blog regarding JSON, as you mentioned:

Related question with data from CSV file: How to run XUnit test using data from a CSV file

And here are two xUnit samples:

FlashOver
  • 1,855
  • 1
  • 13
  • 24
  • 2
    thx, this article really helped https://andrewlock.net/creating-a-custom-xunit-theory-test-dataattribute-to-load-data-from-json-files/ However, I have to rebuild my tests project every time I modify the JSON file. Simply building won't update the file, even if Copy Always is set on the file – Artemious May 01 '20 at 22:54
9

I believe the cleanest way is using ClassData for that so that you can populate data for your test from wherever you like. Consider this:

public class TestData : IEnumerable<object[]> 
{
    private IEnumerable<object[]> ReadFile() 
    {
        //read your file
    }

    public IEnumerator<object[]> GetEnumerator() 
    {
        var items = ReadFile();
        return items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

Of course, you could just populate data from a file during the Arrange phase of your test and then just loop your test method over the data. But in that case, you would lose the advantage of detecting all failing tests instead of just the first.

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Bohdan Stupak
  • 1,455
  • 8
  • 15