Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xUnit test using data coming from external file

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!

like image 567
Giovanni Ruberto Avatar asked Apr 30 '19 14:04

Giovanni Ruberto


People also ask

What is Fact and theory in xUnit?

Fact vs Theory Tests The primary difference between fact and theory tests in xUnit is whether the test has any parameters. Theory tests take multiple different inputs and hold true for a particular set of data, whereas a Fact is always true, and tests invariant conditions.

What class do you inherit from to create a custom attribute that provide test data to data driven tests?

All of these attributes derive from the base DataAttribute class that's part of the xUnit SDK namespace: XUnit. Sdk . In this post I'll show how you can create your own implementation of DataAttribute . This allows you to load data from any source you choose.

Which of the following attributes are eliminated in xUnit?

Thereby, the xUnit test eliminates the risk of test method dependencies.


2 Answers

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:

  • Creating a custom xUnit theory test DataAttribute to load data from JSON files
  • Source on GitHub

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

And here are two xUnit samples:

  • ExcelData
  • SqlData
like image 179
FlashOver Avatar answered Sep 20 '22 03:09

FlashOver


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.

like image 44
Bohdan Stupak Avatar answered Sep 21 '22 03:09

Bohdan Stupak