I was doing unit test using xUnit package for my class library. I would like to try on JSON approach rather than normal object approach for data-driven unit test. However I don't see anywhere that able to achieve this.
What I am stucking at is data-driven test MemberData require the test data to be present in IEnumerable<object[]>
type, when I call data from JSON file, it is in my data model class typed. Do I add them into the IEnumerable<object[]>
? Or there is another way to do it?
Here's the code I have so far:
This is the json file which holds 5 test data:
{
"user": [
{
"name": "John",
"age": 12,
"gender": "Male",
"Hobby": "Reading"
},
{
"name": "Susan",
"age": 34,
"gender": "Female",
"Hobby": "Gardening"
},
{
"name": "Larry",
"age": 24,
"gender": "Male",
"Hobby": "Gaming"
},
{
"name": "Jack",
"age": 3,
"gender": "Male",
"Hobby": "Sleeping"
},
{
"name": "Minnie",
"age": 15,
"gender": "Female",
"Hobby": "Partying"
}
]
}
This is Test class file:
private User GetTestData()
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData.json");
var reader = new StreamReader(filePath);
var jsonStr = reader.ReadToEnd();
var jsonObj = JObject.Parse(jsonStr);
var testDataObj = jsonObj["user"].ToString();
var testData = JsonConvert.DeserializeObject<User>(testDataObj);
return testData;
}
public static IEnumerable<object[]> ValidUserTestData()
{
//What should I do here?
}
[Theory]
[MemberData(nameof(ValidUserTestData))]
public void Test1()
{
}
Is this the correct way to implement this type of test? Or is there any other better options to use JSON file inside data-drive test?
Thank you.