使用 xunit 编写测试代码

xunit 是 .NET 里使用非常广泛的一个测试框架,有很多测试项目都是在使用 xunit 作为测试框架,不仅仅有很多开源项目在使用,很多微软的项目也在使用 xunit 来作为测试框架。

在 xunit 中不需要标记测试方法,所有 public 的类似都可以作为测试类,测试方法需要使用 Fact 或者 Theory 注解来标注方法,来看一个基本的使用示例:

首先准备了几个要测试的方法:

  1. internal class Helper
  2. {
  3. public static int Add(int x, int y)
  4. {
  5. return x + y;
  6. }
  7. public static void ArgumentExceptionTest() => throw new ArgumentException();
  8. public static void ArgumentNullExceptionTest() => throw new ArgumentNullException();
  9. }

测试代码:

  1. public class BasicTest
  2. {
  3. [Fact]
  4. public void AddTest()
  5. {
  6. Assert.Equal(4, Helper.Add(2, 2));
  7. Assert.NotEqual(3, Helper.Add(2, 2));
  8. }
  9. [Theory]
  10. [InlineData(1, 2)]
  11. [InlineData(2, 2)]
  12. public void AddTestWithTestData(int num1, int num2)
  13. {
  14. Assert.Equal(num1 + num2, Helper.Add(num1, num2));
  15. }
  16. }

使用 Fact 标记的测试方法不能方法参数,只有标记 Theory 的方法可以有方法参数

使用 Assert 来断言结果是否符合预期,xunit 提供了很丰富的 Assert 方法,可以使得我们的测试代码更加简洁。

Exception Assert

除了一般的结果断言,xunit 也支持 exception 断言,主要支持两大类,Assert.Throw/Assert.Throw<TExceptionType>/Assert.ThrowAny<TExceptionType>,对应的也有 Async 版本

  1. [Fact]
  2. public void ExceptionTest()
  3. {
  4. var exceptionType = typeof(ArgumentException);
  5. Assert.Throws(exceptionType, Helper.ArgumentExceptionTest);
  6. Assert.Throws<ArgumentException>(testCode: Helper.ArgumentExceptionTest);
  7. }
  8. [Fact]
  9. public void ExceptionAnyTest()
  10. {
  11. Assert.Throws<ArgumentNullException>(Helper.ArgumentNullExceptionTest);
  12. Assert.ThrowsAny<ArgumentNullException>(Helper.ArgumentNullExceptionTest);
  13. Assert.ThrowsAny<ArgumentException>(Helper.ArgumentNullExceptionTest);
  14. }

Assert.Throw(exceptionType, action)Assert.Throw<TExceptionType>(action) 这样的 exception 类型只能是这个类型,继承于这个类型的不算,会 fail,而 Assert.ThrowAny<TExceptionType>(action) 则更包容一点,是这个类型或者是继承于这个类型的都可以。

很多人已经在使用其他的测试框架,如何迁移呢,xunit 也给出了与 nunit 和 mstest 的对比,详细可以参考下面的对比,具体可以参考 https://xunit.net/docs/comparisons

NUnit 3.x MSTest 15.x xUnit.net 2.x Comments
[Test] [TestMethod] [Fact] Marks a test method.
[TestFixture] [TestClass] n/a xUnit.net does not require an attribute for a test class; it looks for all test methods in all public (exported) classes in the assembly.
Assert.That Record.Exception [ExpectedException] Assert.Throws Record.Exception xUnit.net has done away with the ExpectedException attribute in favor of Assert.Throws. See Note 1
[SetUp] [TestInitialize] Constructor We believe that use of [SetUp] is generally bad. However, you can implement a parameterless constructor as a direct replacement. See Note 2
[TearDown] [TestCleanup] IDisposable.Dispose We believe that use of [TearDown] is generally bad. However, you can implement IDisposable.Dispose as a direct replacement. See Note 2
[OneTimeSetUp] [ClassInitialize] IClassFixture<T> To get per-class fixture setup, implement IClassFixture<T> on your test class. See Note 3
[OneTimeTearDown] [ClassCleanup] IClassFixture<T> To get per-class fixture teardown, implement IClassFixture<T> on your test class. See Note 3
n/a n/a ICollectionFixture<T> To get per-collection fixture setup and teardown, implement ICollectionFixture<T> on your test collection. See Note 3
[Ignore("reason")] [Ignore] [Fact(Skip="reason")] Set the Skip parameter on the [Fact] attribute to temporarily skip a test.
[Property] [TestProperty] [Trait] Set arbitrary metadata on a test
[Theory] [DataSource] [Theory] [XxxData] Theory (data-driven test). See Note 4

测试框架大多提供数据驱动测试的支持,简单的就如开篇中的 Theory 示例,我们再来看一些稍微复杂一些的示例,一起来看下:

要使用数据驱动的方式写测试方法,测试方法应该标记为 Theory,并且将测试数据作为测试方法的方法参数

最基本数据驱动的方式当属 InlineData,添加多个 InlineData 即可使用不同的测试数据进行测试

  1. [Theory]
  2. [InlineData(1)]
  3. [InlineData(2)]
  4. [InlineData(3)]
  5. public void InlineDataTest(int num)
  6. {
  7. Assert.True(num > 0);
  8. }

InlineData 有其限制,只能使用一些常量,想要更灵活的方式需要使用别的方式,测试结果:

MemberData 可以一定程度上解决 InlineData 存在的问题,MemberData 支持字段、属性或方法,且需要满足下面两个条件:

  • 需要是 public

  • 需要是 static

  • 可以隐式转换为 IEnumerable<object[]> 或者方法返回值可以隐式转换为 IEnumerable<object[]>

来看下面的示例:

  1. [Theory]
  2. [MemberData(nameof(TestMemberData))]
  3. public void MemberDataPropertyTest(int num)
  4. {
  5. Assert.True(num > 0);
  6. }
  7. public static IEnumerable<object[]> TestMemberData =>
  8. Enumerable.Range(1, 10)
  9. .Select(x => new object[] { x })
  10. .ToArray();
  11. [Theory]
  12. [MemberData(nameof(TestMemberDataField))]
  13. public void MemberDataFieldTest(int num)
  14. {
  15. Assert.True(num > 0);
  16. }
  17. public static readonly IList<object[]> TestMemberDataField = Enumerable.Range(1, 10).Select(x => new object[] { x }).ToArray();
  18. [Theory]
  19. [MemberData(nameof(TestMemberDataMethod), 10)]
  20. public void MemberDataMethodTest(int num)
  21. {
  22. Assert.True(num > 0);
  23. }
  24. public static IEnumerable<object[]> TestMemberDataMethod(int count)
  25. {
  26. return Enumerable.Range(1, count).Select(i => new object[] { i });
  27. }

测试结果:

MemberData 相比之下提供了更大的便利和可自定义程度,只能在当前测试类中使用,想要跨测试类还是不行,xunit 还提供了 DataAttribute ,使得我们可以通过自定义方式实现测试方法数据源,甚至也可以从数据库里动态查询出数据,写了一个简单的示例,可以参考下面的示例:

自定义数据源:

  1. public class NullOrEmptyStringDataAttribute : DataAttribute
  2. {
  3. public override IEnumerable<object[]> GetData(MethodInfo testMethod)
  4. {
  5. yield return new object[] { null };
  6. yield return new object[] { string.Empty };
  7. }
  8. }

测试方法:

  1. [Theory]
  2. [NullOrEmptyStringData]
  3. public void CustomDataAttributeTest(string value)
  4. {
  5. Assert.True(string.IsNullOrEmpty(value));
  6. }

测试结果:

在测试方法中如果想要输出一些测试信息,直接是用 Console.Write/Console.WriteLine 是没有效果的,在测试方法中输出需要使用 ITestoutputHelper 来输出,来看下面的示例:

  1. public class OutputTest
  2. {
  3. private readonly ITestOutputHelper _outputHelper;
  4. public OutputTest(ITestOutputHelper outputHelper)
  5. {
  6. _outputHelper = outputHelper;
  7. }
  8. [Fact]
  9. public void ConsoleWriteTest()
  10. {
  11. Console.WriteLine("Console");
  12. }
  13. [Fact]
  14. public void OutputHelperTest()
  15. {
  16. _outputHelper.WriteLine("Output");
  17. }
  18. }

测试方法中使用 Console.Write/Console.WriteLine 的时候会有一个提示:

测试输出结果:

Console.WriteLine

TestOutputHelper.WriteLine

xunit 提供了 BeforeAfterTestAttribute 来让我们实现一些自定义的逻辑来在测试运行前和运行后执行,和 mvc 里的 action filter 很像,所以这里我把他称为 test filter,来看下面的一个示例,改编自 xunit 的示例:

  1. /// <summary>
  2. /// Apply this attribute to your test method to replace the
  3. /// <see cref="Thread.CurrentThread" /> <see cref="CultureInfo.CurrentCulture" /> and
  4. /// <see cref="CultureInfo.CurrentUICulture" /> with another culture.
  5. /// </summary>
  6. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
  7. public class UseCultureAttribute : BeforeAfterTestAttribute
  8. {
  9. private readonly Lazy<CultureInfo> _culture;
  10. private readonly Lazy<CultureInfo> _uiCulture;
  11. private CultureInfo _originalCulture;
  12. private CultureInfo _originalUiCulture;
  13. /// <summary>
  14. /// Replaces the culture and UI culture of the current thread with
  15. /// <paramref name="culture" />
  16. /// </summary>
  17. /// <param name="culture">The name of the culture.</param>
  18. /// <remarks>
  19. /// <para>
  20. /// This constructor overload uses <paramref name="culture" /> for both
  21. /// <see cref="Culture" /> and <see cref="UICulture" />.
  22. /// </para>
  23. /// </remarks>
  24. public UseCultureAttribute(string culture)
  25. : this(culture, culture) { }
  26. /// <summary>
  27. /// Replaces the culture and UI culture of the current thread with
  28. /// <paramref name="culture" /> and <paramref name="uiCulture" />
  29. /// </summary>
  30. /// <param name="culture">The name of the culture.</param>
  31. /// <param name="uiCulture">The name of the UI culture.</param>
  32. public UseCultureAttribute(string culture, string uiCulture)
  33. {
  34. _culture = new Lazy<CultureInfo>(() => new CultureInfo(culture, false));
  35. _uiCulture = new Lazy<CultureInfo>(() => new CultureInfo(uiCulture, false));
  36. }
  37. /// <summary>
  38. /// Gets the culture.
  39. /// </summary>
  40. public CultureInfo Culture { get { return _culture.Value; } }
  41. /// <summary>
  42. /// Gets the UI culture.
  43. /// </summary>
  44. public CultureInfo UICulture { get { return _uiCulture.Value; } }
  45. /// <summary>
  46. /// Stores the current <see cref="Thread.CurrentPrincipal" />
  47. /// <see cref="CultureInfo.CurrentCulture" /> and <see cref="CultureInfo.CurrentUICulture" />
  48. /// and replaces them with the new cultures defined in the constructor.
  49. /// </summary>
  50. /// <param name="methodUnderTest">The method under test</param>
  51. public override void Before(MethodInfo methodUnderTest)
  52. {
  53. _originalCulture = Thread.CurrentThread.CurrentCulture;
  54. _originalUiCulture = Thread.CurrentThread.CurrentUICulture;
  55. Thread.CurrentThread.CurrentCulture = Culture;
  56. Thread.CurrentThread.CurrentUICulture = UICulture;
  57. CultureInfo.CurrentCulture.ClearCachedData();
  58. CultureInfo.CurrentUICulture.ClearCachedData();
  59. }
  60. /// <summary>
  61. /// Restores the original <see cref="CultureInfo.CurrentCulture" /> and
  62. /// <see cref="CultureInfo.CurrentUICulture" /> to <see cref="Thread.CurrentPrincipal" />
  63. /// </summary>
  64. /// <param name="methodUnderTest">The method under test</param>
  65. public override void After(MethodInfo methodUnderTest)
  66. {
  67. Thread.CurrentThread.CurrentCulture = _originalCulture;
  68. Thread.CurrentThread.CurrentUICulture = _originalUiCulture;
  69. CultureInfo.CurrentCulture.ClearCachedData();
  70. CultureInfo.CurrentUICulture.ClearCachedData();
  71. }
  72. }

这里实现了一个设置测试用例运行过程中 Thread.CurrentThread.Culture 的属性,测试结束后恢复原始的属性值,可以用作于 Class 也可以用在测试方法中,使用示例如下:

  1. [UseCulture("en-US", "zh-CN")]
  2. public class FilterTest
  3. {
  4. [Fact]
  5. [UseCulture("en-US")]
  6. public void CultureTest()
  7. {
  8. Assert.Equal("en-US", Thread.CurrentThread.CurrentCulture.Name);
  9. }
  10. [Fact]
  11. [UseCulture("zh-CN")]
  12. public void CultureTest2()
  13. {
  14. Assert.Equal("zh-CN", Thread.CurrentThread.CurrentCulture.Name);
  15. }
  16. [Fact]
  17. public void CultureTest3()
  18. {
  19. Assert.Equal("en-US", Thread.CurrentThread.CurrentCulture.Name);
  20. Assert.Equal("zh-CN", Thread.CurrentThread.CurrentUICulture.Name);
  21. }
  22. }

测试结果如下:

单元测试类通常共享设置和清除代码(通常称为“测试上下文”)。 xunit 提供了几种共享设置和清除代码的方法,具体取决于要共享的对象的范围。

通常我们可以使用 Fixture 来实现依赖注入,但是我更推荐使用 Xunit.DependencyInjection 这个项目来实现依赖注入,具体使用可以参考之前的文章 在 xunit 测试项目中使用依赖注入 中的介绍

希望对你使用 xunit 有所帮助

文章中的示例代码可以从 https://github.com/WeihanLi/SamplesInPractice/tree/master/XunitSample 获取

xunit 还有很多可以扩展的地方,更多可以参考 xunit 的示例 https://github.com/xunit/samples.xunit

版权声明:本文为weihanli原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/weihanli/p/14456785.html