Showing posts with label Unit Testing. Show all posts
Showing posts with label Unit Testing. Show all posts

Monday, November 14, 2016

xUnit Theory test ClassData with complex type

xUnit.net is a powerful, free, open source, unit testing tool for the .NET Framework. xUnit uses different notation to NUnit or MSUnit to specify test with parameters. Here I am going to show how to use Theory ClassData with complex type.



I have a sample class Plant, which has function 'bool IsEqual(Plant plant);'. We will create a Theory test for it.


[Theory]
[ClassData(typeof(IsEqualTestData))]
public void IsEqual(Plant plant1, Plant plant2, bool expectedResult)
{
Assert.Equal(expectedResult, plant1.IsEqual(plant2));
}


Class IsEqualTestData is a ClassData used with complex type Plant. It generates a list of arrays of 3 objects Plant1, Plant2, and ExpectedResult boolean.



private
class IsEqualTestData : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[]
{
new Plant()
{
Name = PlantTester.PlantName1,
Description = PlantTester.PlantDescription1
},
new Plant()
{
Name = PlantTester.PlantName2,
Description = PlantTester.PlantDescription2
},
false
},
new object[]
{
new Plant() { Name = PlantTester.PlantName1 },
new Plant() { Name = PlantTester.PlantName1 },
true
},
new object[]
{
new Plant()
{
Name = PlantTester.PlantName1,
Description = PlantTester.PlantDescription1
},
new Plant()
{
Name = PlantTester.PlantName2,
Description = PlantTester.PlantDescription1
},
true
}
};

public IEnumerator<object[]> GetEnumerator()
{
return _data.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}


When running in xUnit it will report result of running each entry in the test.



If you are using Visual Studio you can download snippet file from github repository.




Reference:


xUnit_ClassData.snippet

Using dotnet watch test for continuous testing with .NET Core and XUnit.net - Scott Hanselman
0