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!
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.
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.
Thereby, the xUnit test eliminates the risk of test method dependencies.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With