C#中的测试框架(XUnit, NUnit)

单元测试

单元测试(unit testing),是指对软件中的最小可测试单元(函数/模块/类)进行检查和验证。
单元测试是在软件开发过程中要进行的最低级别的测试活动,软件的独立单元将在与程序的其他部分相隔离的情况下进行测试。
单元测试从长期来看,可以提高代码质量,减少维护成本,降低重构难度。但是从短期来看,加大了工作量,对于进度紧张的项目中的开发人员来说,可能会成为不少的负担。
单元测试应该遵循以下原则:可靠性、可维护性、可读性;
尽量避免测试中的逻辑,一个单元测试应该是一系列的方法调用和断言;
避免重复代码;
测试隔离,低耦合,防止不同测试之间的互相影响。

C#中的测试框架.

  • XUnit

NUnit is a unit-testing framework for all .NET languages. Initially ported from JUnit, the current production release, version 3, has been completely rewritten with many new features and support for a wide range of .NET platforms.

  • NUnit

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other .NET languages. xUnit.net works with ReSharper, CodeRush, TestDriven.NET and Xamarin. It is part of the .NET Foundation, and operates under their code of conduct.

  • MSTest

MSTest是一款由微软公司开发的单元测试框架,它能够很好地被应用在Visual Studio中,并且集成在了Visual Studio单元测试框架中。但是最近几年从Dotnet Core以后,使用得很少,就不过多介绍了。

测试的步骤

Arrange:在这里做一些先决的设定。例如创建对象实例,数据,输入等。
Act:在这里执行生产代码并返回结果。例如调用方法或者设置属性。
Assert:在这里检查结果,会产生测试通过或者失败两种结果。

xUnit案例

xUnit中对于传参及多个测试情况可以使用TheoryInlineData两个属性

  • Theory 表示执行相同代码,但具有不同输入参数的测试套件。

  • InlineData属性指定这些输入的值。

// 直接使用[Fact]public void IsPrime_InputIs1_ReturnFalse(){    var primeService = new PrimeService();    bool result = primeService.IsPrime(1);
    Assert.False(result, "1 should not be prime");}
// 传参测试[Theory][InlineData(-1)][InlineData(0)][InlineData(1)]public void IsPrime_ValuesLessThan2_ReturnFalse(int value){    var result = _primeService.IsPrime(value);
    Assert.False(result, $"{value} should not be prime");}