Xunit笔记-属性标签
步骤:
- 创建Xunit测试项目
- 运行测试项目后,菜单栏会出现“测试”,测试-窗口-测试资源管理器
- 进入测试资源管理器后,点击全部运行即可
测试方法属性标签:
Fact:
[Fact]用于无参测试方法
[Fact]
public void FailingTest()
{
Assert.Equal(5, Add(2, 2));
}
Theory:
[Theory]配合[InlineData]可以直接在一个方法中测试多组参数,每一组参数会执行一次方法
[Theory]
[InlineData(3)]
[InlineData(5)]
[InlineData(6)]
public void MyFirstTheory(int value)
{
Assert.True(IsOdd(value));
}
[Fact]和[Theory]还可以带两个参数,一个是修改显示名称,一个是跳过测试
[Fact(DisplayName ="通过测试")]
public void PassingTest()
{
Assert.Equal(4, Add(2, 2));
}
[Fact(Skip ="跳过测试")]
public void FailingTest()
{
Assert.Equal(5, Add(2, 2));
}
MemberData特性:
还可以使用[MemberData],测试多组参数,代码更简洁
public class InternalHealthDamageTestData
{
private static readonly List<object[]> Data = new List<object[]>
{
new object[] {0, 100},
new object[] {1, 99},
new object[] {50, 50},
new object[] {101, 1}
};
public static IEnumerable<object[]> TestData => Data;
}
public class NonPlayerCharacterShould
{
[Theory]
[MemberData(nameof(InternalHealthDamageTestData.TestData), MemberType = typeof(InternalHealthDamageTestData))]
public void TakeDamage(int damage, int expectedHealth)
{
NonPlayerCharacter sut = new NonPlayerCharacter();
sut.TakeDamage(damage);
Assert.Equal(expectedHealth, sut.Health);
}
}
CustomDataAttribute特性
用来自定义数据属性标签
public class HealthDamageDataAttribute : DataAttribute
{
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
yield return new object[] { 0, 100 };
yield return new object[] { 1, 99 };
yield return new object[] { 50, 50 };
yield return new object[] { 101, 1 };
}
}
public class NonPlayerCharacterShould
{
[Theory]
[HealthDamageData]
public void TakeDamage(int damage, int expectedHealth)
{
NonPlayerCharacter sut = new NonPlayerCharacter();
sut.TakeDamage(damage);
Assert.Equal(expectedHealth, sut.Health);
}
}