举例说明 .Net Core 单元测试中 xUnit 的 [Theory] 属性的用法

在这篇文章中,我们探讨了如何使用 xUnit 的 [Theory] 属性来运行参数化测试。通过示例展示了如何使用 [InlineData][MemberData][ClassData] 提供不同的数据源,从而简化测试代码并提高测试覆盖率。这些方法有助于在 .NET 应用程序中进行更有效的单元测试。

示例 1:使用 [InlineData]

这是直接在属性中提供数据的最简单方法。

using Xunit;

public class MathTests
{
    [Theory]
    [InlineData(1, 1, 2)]
    [InlineData(2, 3, 5)]
    [InlineData(10, -5, 5)]
    public void Add_ReturnsCorrectSum(int a, int b, int expectedSum)
    {
        // Arrange
        var math = new Math();

        // Act
        var result = math.Add(a, b);

        // Assert
        Assert.Equal(expectedSum, result);
    }
}

public class Math
{
    public int Add(int x, int y) => x + y;
}

示例 2:使用 [MemberData]

这允许你引用返回 IEnumerable<object[]> 的方法或属性。

using Xunit;
using System.Collections.Generic;

public class MathTests
{
    public static IEnumerable<object[]> AddData =>
        new List<object[]>
        {
            new object[] { 1, 1, 2 },
            new object[] { 2, 3, 5 },
            new object[] { 10, -5, 5 }
        };

    [Theory]
    [MemberData(nameof(AddData))]
    public void Add_ReturnsCorrectSum(int a, int b, int expectedSum)
    {
        // Arrange
        var math = new Math();

        // Act
        var result = math.Add(a, b);

        // Assert
        Assert.Equal(expectedSum, result);
    }
}

public class Math
{
    public int Add(int x, int y) => x + y;
}

示例 3:使用 [ClassData]

这对于更复杂的数据设置非常有用。你可以创建一个实现 IEnumerable<object[]> 的类。

using Xunit;
using System.Collections;
using System.Collections.Generic;

public class MathTests
{
    [Theory]
    [ClassData(typeof(AddTestData))]
    public void Add_ReturnsCorrectSum(int a, int b, int expectedSum)
    {
        // Arrange
        var math = new Math();

        // Act
        var result = math.Add(a, b);

        // Assert
        Assert.Equal(expectedSum, result);
    }
}

public class AddTestData : IEnumerable<object[]>
{
    public IEnumerator<object[]> GetEnumerator()
    {
        yield return new object[] { 1, 1, 2 };
        yield return new object[] { 2, 3, 5 };
        yield return new object[] { 10, -5, 5 };
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

public class Math
{
    public int Add(int x, int y) => x + y;
}

总结

通过本文的介绍,我们了解了如何使用 xUnit 的 [Theory] 属性来进行参数化测试。无论是使用 [InlineData] 直接提供数据,还是通过 [MemberData][ClassData] 引用外部数据源,这些方法都能帮助我们编写更灵活和高效的单元测试。掌握这些技巧,可以显著提升 .NET 应用程序的测试覆盖率和代码质量,为开发过程带来更多便利和保障。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

surfirst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值