Skip to content

Commit 9963191

Browse files
committed
Enhance documentation for TheoryData, MemberData, and ClassData in xUnit with additional examples and explanations
1 parent 97a230c commit 9963191

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

docs/UnitTest/3 Class.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
- So TheoryData is a built-in class in xUnit that helps you manage and provide complex data sets for parameterized tests.
55
- It allows you to create **strongly-typed** collections of data that can be used with the `[Theory]` attribute.
66
- This is good replace for using `IEnumerable<object[]>` for complex data sets.
7+
- Advantages of using `TheoryData` over `IEnumerable<object[]>`:
8+
- **Type Safety**: Since `TheoryData` is strongly typed, it helps catch type-related errors at compile time rather than at runtime.
9+
- **Readability**: The structure of `TheoryData` makes it easier to understand the data being provided to the test methods.
10+
- **Intellisense Support**: When using `TheoryData`, you get better IntelliSense support in IDEs, making it easier to work with the data.
711

12+
### MemberData with TheoryData
813
```csharp
914
[Theory]
1015
[MemberData(nameof(GetDistanceTestData))]
@@ -28,3 +33,54 @@ public static TheoryData<Point2D, Point2D, double> GetDistanceTestData()
2833
}
2934
```
3035

36+
```csharp
37+
public class Point2DTest
38+
{
39+
[Theory]
40+
[MemberData(nameof(TestDataPoint2D.Distance), MemberType = typeof(TestDataPoint2D))]
41+
public void TestDistanceTo_WithMemberData(Point2D pointA, Point2D pointB, double expectedDistance)
42+
{
43+
//Act
44+
var distance = pointA.DistanceTo(pointB);
45+
//Assert
46+
Assert.Equal(expectedDistance, distance, 3);
47+
}
48+
}
49+
public static class TestDataPoint2D
50+
{
51+
public static TheoryData<Point2D, Point2D, double> Distance()
52+
{
53+
var data = new TheoryData<Point2D, Point2D, double>();
54+
data.Add(new Point2D(0, 0), new Point2D(10, 0), 10);
55+
data.Add(new Point2D(0, 0), new Point2D(10, 10), 14.1421);
56+
data.Add(new Point2D(1, 2), new Point2D(3, 4), 2.8284);
57+
return data;
58+
}
59+
}
60+
```
61+
62+
### ClassData with TheoryData
63+
```csharp
64+
public class Point2DTest
65+
{
66+
[Theory]
67+
[ClassData(typeof(DistanceTestData))]
68+
public void TestDistanceTo_WithMemberData(Point2D pointA, Point2D pointB, double expectedDistance)
69+
{
70+
//Act
71+
var distance = pointA.DistanceTo(pointB);
72+
//Assert
73+
Assert.Equal(expectedDistance, distance, 3);
74+
}
75+
}
76+
77+
public class DistanceTestData : TheoryData<Point2D, Point2D, double>
78+
{
79+
public DistanceTestData()
80+
{
81+
Add(new Point2D(0, 0), new Point2D(3, 4), 5.0);
82+
Add(new Point2D(1, 1), new Point2D(4, 5), 5.0);
83+
Add(new Point2D(-1, -1), new Point2D(2, 3), 5.0);
84+
}
85+
}
86+
```

0 commit comments

Comments
 (0)