一、xUnit 单元测试
官网地址:Home > xUnit.net
1、概述
1.1、新建个控制台项目
cs
public class Class1
{
public int Add(int x, int y)
{
return x + y;
}
}
2、建个xUnit测试项目
cs
public class UnitTest1
{
[Fact]
public void Test1()
{
Class1 class1 = new Class1();
int sum = class1.Add(2, 3);
Assert.Equal(5, sum);
}
}
鼠标放到方法上,右键运行测试即可
2、用法
2.1、基础应用
cs
public class UnitTest1
{
private readonly ITestOutputHelper _outputHelper;
public UnitTest1(ITestOutputHelper testOutput)
{
_outputHelper = testOutput;
}
[Fact]
//[Trait("name","kawa1")]
public void Test1()
{
_outputHelper.WriteLine("第一个测试");//自定义测试输出信息
Class1 class1 = new Class1();
int sum = class1.Add(2, 3);
Assert.Equal(5, sum);//以下断言皆为true
string name = "come kawa";
Assert.True(1==1);
Assert.StartsWith("come",name);
Assert.Contains("ka", name);
Assert.NotEqual("come ka", name);
Assert.Matches(@"^[a-z]*\s[a-z]*", name);
Assert.InRange(sum, 3.1, 6.9);//是否在某一范围
Assert.NotNull(name);
Assert.IsType<Class1>(class1);
}
}
[Fact(Skip = "不跑这个测试")]//忽略测试
[Trait("name","kawa1")] //分组
2.2、数据驱动测试
cs
1、
[Theory]
[InlineData(1,2,3)]
[InlineData(3,4,7)]
[InlineData(4,2,6)]
public void Test2(int x, int y, int except)
{
int act = new Class1().Add(x, y);
Assert.Equal(act, except);
}
2、
[Theory]
[MemberData(nameof(Class1.ListTest),MemberType = typeof(Class1))]
public void Test3(int x, int y, int except)
{
_outputHelper.WriteLine("Test3测试");//自定义测试输出信息
int act = new Class1().Add(x, y);
Assert.Equal(except, act);
}
public static List<object[]> ListTest = new List<object[]> //需要是object类型且是静态
{
new object[] { 1, 2 ,3},
new object[] { 2, 3 ,5 },
new object[] { 3, 6 ,9 }
};
3、自定义Data Attribute
[Theory]
[DataTest]
public void Test4(int x, int y, int except)
{
_outputHelper.WriteLine("Test4测试");//自定义测试输出信息
int act = new Class1().Add(x, y);
Assert.Equal(except, act);
}
public class DataTestAttribute: DataAttribute
{
//继承DataAttribute,并重写GetData
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
yield return new object[] { 0, 100, 100 };
yield return new object[] { 1, 100, 101 };
yield return new object[] { 200, 100, 300 };
yield return new object[] { 15, 100, 115 };
}
}