第1部分: http://www.cnblogs.com/cgzl/p/8283610.html

第2部分: http://www.cnblogs.com/cgzl/p/8287588.html

请使用这个项目作为练习的开始: https://pan.baidu.com/s/1ggcGkGb

测试的分组

打开Game.Tests里面的BossEnemyShould.cs, 为HaveCorrectPower方法添加一个Trait属性标签:

        [Fact][Trait("Category", "Enemy")]public void HaveCorrectPower(){BossEnemy sut = new BossEnemy();Assert.Equal(166.667, sut.SpecialAttackPower, 3);}

Trait接受两个参数, 作为测试分类的Name和Value对.

Build项目, Run All Tests, 然后选择选择一下按Traits分组:

这时, Test Explorer里面的tests将会这样显示:

再打开EnemyFactoryShould.cs, 为CreateNormalEnemyByDefault方法添加Trait属性标签:

        [Fact][Trait("Category", "Enemy")]public void CreateNormalEnemyByDefault(){EnemyFactory sut = new EnemyFactory();Enemy enemy = sut.Create("Zombie");Assert.IsType<NormalEnemy>(enemy);}

Build, 然后查看Test Explorer:

不同的Category:

修改一下BossEnemyShould.cs里面的HaveCorrectPower方法的Trait属性:

        [Fact][Trait("Category", "Boss")]public void HaveCorrectPower(){BossEnemy sut = new BossEnemy();Assert.Equal(166.667, sut.SpecialAttackPower, 3);}

Build之后, 将会看见两个分类:

在Class级别进行分类:

只需要把Trait属性标签移到Class上面即可:

    [Trait("Category", "Enemy")]public class EnemyFactoryShould{

Build, 查看Test Explorer可以发现EnemyFactoryShould下面所有的Test方法都分类到了Enemy下:

按分类运行测试:

鼠标右键点击分类, Run Selected Tests就会运行该分类下所有的测试:

按Trait搜索:

在Test Explorer中把分类选择到Class:

然后在旁边的Search输入框中输入关键字, 这时下方会有提示菜单:

点击Trait, 然后如下图输入, 就会把Enemy分类的测试过滤显示出来:

这种方式同样也可以进行Trait过滤.

使用命令行进行分类测试

使用命令行进入的Game.Tests, 首先执行命令dotnet test, 这里显示一共有27个tests:

然后, 可以使用命令:

dotnet test --filter Category=Enemy

运行分类为Enemy的tests, 结果如图, 有8个tests:

运行多个分类的tests:

dotnet test --filter "Category=Boss|Category=Enemy"

这句命令会运行分类为Boss或者Enemy的tests, 结果如图:

共有9个tests.

忽略Test

为Fact属性标签设置其Skip属性, 即可忽略该测试, Skip的值为忽略的原因:

        [Fact(Skip = "不需要跑这个测试")]public void CreateNormalEnemyByDefault_NotTypeExample(){EnemyFactory sut = new EnemyFactory();Enemy enemy = sut.Create("Zombie");Assert.IsNotType<DateTime>(enemy);}

Build, 查看Test Explorer, 选择按Trait分类显示, 然后选中Category[Enemy]运行选中的tests:

从这里可以看到, 上面Skip的test被忽略了.

回到命令行, 执行dotnet test:

也可以看到该测试被忽略了, 并且标明了忽略的原因.

打印自定义测试输出信息:

在test中打印信息需要用到ITestOutputHelper的实现类(注意: 这里使用Console.Writeline是无效的), 在BossEnemyShould.cs里面注入这个helper:

using Xunit;
using Xunit.Abstractions;namespace Game.Tests
{public class BossEnemyShould{private readonly ITestOutputHelper _output;public BossEnemyShould(ITestOutputHelper output){_output = output;}......

然后在test方法里面这样写即可:

        [Fact][Trait("Category", "Boss")]public void HaveCorrectPower(){_output.WriteLine("正在创建 Boss Enemy");BossEnemy sut = new BossEnemy();Assert.Equal(166.667, sut.SpecialAttackPower, 3);}

Build, Run Tests, 这时查看测试结果会发现一个output链接:

点击这个链接, 就会显示测试的输出信息:

使用命令行:

dotnet test --filter Category=Boss --logger:trx

执行命令后:

可以看到生成了一个TestResults文件夹, 里面是测试的输出文件, 使用编辑器打开, 它是一个xml文件, 内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<TestRun id="9e552b73-0636-46a2-83d9-c19a5892b3ab" name="solen@DELL-RED 2018-02-10 10:27:19" runUser="DELL-RED\solen" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"><Times creation="2018-02-10T10:27:19.5005784+08:00" queuing="2018-02-10T10:27:19.5005896+08:00" start="2018-02-10T10:27:17.4990291+08:00" finish="2018-02-10T10:27:19.5176327+08:00" /><TestSettings name="default" id="610cad4c-1066-417b-a8e6-d30dce78ef4d"><Deployment runDeploymentRoot="solen_DELL-RED_2018-02-10_10_27_19" /></TestSettings><Results><UnitTestResult executionId="4c6ec739-ccd3-4233-b2bd-8bbde4dfa67f" testId="9e476ed4-3cd9-4f51-aa39-b3d411369979" testName="Game.Tests.BossEnemyShould.HaveCorrectPower" computerName="DELL-RED" duration="00:00:00.0160000" startTime="2018-02-10T10:27:19.2099922+08:00" endTime="2018-02-10T10:27:19.2113656+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="4c6ec739-ccd3-4233-b2bd-8bbde4dfa67f"><Output><StdOut>正在创建 Boss Enemy</StdOut></Output></UnitTestResult></Results><TestDefinitions><UnitTest name="Game.Tests.BossEnemyShould.HaveCorrectPower" storage="c:\users\solen\projects\game\game.tests\bin\debug\netcoreapp2.0\game.tests.dll" id="9e476ed4-3cd9-4f51-aa39-b3d411369979"><Execution id="4c6ec739-ccd3-4233-b2bd-8bbde4dfa67f" /><TestMethod codeBase="C:\Users\solen\projects\Game\Game.Tests\bin\Debug\netcoreapp2.0\Game.Tests.dll" executorUriOfAdapter="executor://xunit/VsTestRunner2/netcoreapp" className="Game.Tests.BossEnemyShould" name="Game.Tests.BossEnemyShould.HaveCorrectPower" /></UnitTest></TestDefinitions><TestEntries><TestEntry testId="9e476ed4-3cd9-4f51-aa39-b3d411369979" executionId="4c6ec739-ccd3-4233-b2bd-8bbde4dfa67f" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" /></TestEntries><TestLists><TestList name="Results Not in a List" id="8c84fa94-04c1-424b-9868-57a2d4851a1d" /><TestList name="All Loaded Results" id="19431567-8539-422a-85d7-44ee4e166bda" /></TestLists><ResultSummary outcome="Completed"><Counters total="1" executed="1" passed="1" failed="0" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" /><Output><StdOut>[xUnit.net 00:00:00.5525795]   Discovering: Game.Tests[xUnit.net 00:00:00.6567207]   Discovered:  Game.Tests[xUnit.net 00:00:00.6755272]   Starting:    Game.Tests[xUnit.net 00:00:00.8743059]   Finished:    Game.Tests</StdOut></Output></ResultSummary>
</TestRun>

View Code

在里面某个Output标签内可以看到上面写的测试输出信息.

减少重复的代码

xUnit在执行某个测试类的Fact或Theory方法的时候, 都会创建这个类新的实例, 所以有一些公用初始化的代码可以移动到constructor里面.

打开PlayerCharacterShould.cs, 可以看到每个test方法都执行了new PlayerCharacter()这个动作. 我们应该把这段代码移动到constructor里面:

namespace Game.Tests
{public class PlayerCharacterShould{private readonly PlayerCharacter _playerCharacter;private readonly ITestOutputHelper _output;public PlayerCharacterShould(ITestOutputHelper output){       _output = output;            _output.WriteLine("正在创建新的玩家角色");_playerCharacter = new PlayerCharacter();}[Fact]public void BeInexperiencedWhenNew(){Assert.True(_playerCharacter.IsNoob);}[Fact]public void CalculateFullName(){_playerCharacter.FirstName = "Sarah";_playerCharacter.LastName = "Smith";Assert.Equal("Sarah Smith", _playerCharacter.FullName);......

Build, Run Tests, 都OK, 并且都有output输出信息.

除了集中编写初始化代码, 也可以集中编写清理代码:

这需要该测试类实现IDisposable接口:

public class PlayerCharacterShould: IDisposable{......public void Dispose(){_output.WriteLine($"正在清理玩家{_playerCharacter.FullName}");}}

Build, Run Tests, 然后随便查看一个该类的test的output:

可以看到Dispose()被调用了.

在执行测试的时候共享上下文

上面降到了每个测试方法运行的时候都会创建该测试类新的实例, 可以在constructor里面进行公共的初始化动作.

但是如果初始化的动作消耗资源比较大, 并且时间较长, 那么这种方法就不太好了, 所以下面介绍另外一种方法.

首先在Game项目里面添加类:GameState.cs:

using System;
using System.Collections.Generic;namespace Game
{public class GameState{public static readonly int EarthquakeDamage = 25;public List<PlayerCharacter> Players { get; set; } = new List<PlayerCharacter>();public Guid Id { get; } = Guid.NewGuid();public GameState(){CreateGameWorld();}        public void Earthquake(){foreach (var player in Players){player.TakeDamage(EarthquakeDamage);}}public void Reset(){Players.Clear();}private void CreateGameWorld(){// Simulate expensive creationSystem.Threading.Thread.Sleep(2000);}}
}

View Code

在Game.Tests里面添加类: GameStateShould.cs:

using Xunit;namespace Game.Tests
{public class GameStateShould{[Fact]public void DamageAllPlayersWhenEarthquake(){var sut = new GameState();var player1 = new PlayerCharacter();var player2 = new PlayerCharacter();sut.Players.Add(player1);sut.Players.Add(player2);var expectedHealthAfterEarthquake = player1.Health - GameState.EarthquakeDamage;sut.Earthquake();Assert.Equal(expectedHealthAfterEarthquake, player1.Health);Assert.Equal(expectedHealthAfterEarthquake, player2.Health);}[Fact]public void Reset(){var sut = new GameState();var player1 = new PlayerCharacter();var player2 = new PlayerCharacter();sut.Players.Add(player1);sut.Players.Add(player2);sut.Reset();Assert.Empty(sut.Players);            }}
}

View Code

看一下上面的代码, 里面有一个Sleep 2秒的动作, 所以执行两个测试方法的话每个方法都会执行这个动作, 一共用了这些时间:

为了解决这个问题, 我们首先建立一个类 GameStateFixture.cs, 它需要实现IDisposable接口:

using System;namespace Game.Tests
{public class GameStateFixture : IDisposable{public GameState State { get; private set; }public GameStateFixture(){State = new GameState();}public void Dispose(){// Cleanup
        }}
}

然后在GameStateShould类实现IClassFixture接口并带有泛型的类型:

using Xunit;
using Xunit.Abstractions;namespace Game.Tests
{public class GameStateShould : IClassFixture<GameStateFixture>{private readonly GameStateFixture _gameStateFixture;private readonly ITestOutputHelper _output;public GameStateShould(GameStateFixture gameStateFixture, ITestOutputHelper output){_gameStateFixture = gameStateFixture;_output = output;}[Fact]public void DamageAllPlayersWhenEarthquake(){_output.WriteLine($"GameState Id={_gameStateFixture.State.Id}");var player1 = new PlayerCharacter();var player2 = new PlayerCharacter();_gameStateFixture.State.Players.Add(player1);_gameStateFixture.State.Players.Add(player2);var expectedHealthAfterEarthquake = player1.Health - GameState.EarthquakeDamage;_gameStateFixture.State.Earthquake();Assert.Equal(expectedHealthAfterEarthquake, player1.Health);Assert.Equal(expectedHealthAfterEarthquake, player2.Health);}[Fact]public void Reset(){_output.WriteLine($"GameState Id={_gameStateFixture.State.Id}");var player1 = new PlayerCharacter();var player2 = new PlayerCharacter();_gameStateFixture.State.Players.Add(player1);_gameStateFixture.State.Players.Add(player2);_gameStateFixture.State.Reset();Assert.Empty(_gameStateFixture.State.Players);            }}
}

这个注入的_gameStateFixture在运行多个tests的时候只有一个实例. 所以把消耗资源严重的动作放在GameStateFixture里面就可以保证该段代码只运行一次, 并且被所有的test所共享调用. 要注意的是, 因为上述原因, GameStateFixture里面的代码不可以有任何副作用, 也就是说可以影响其他的测试结果.

Build, Run Tests:

可以看到运行时间少了很多, 因为那段Sleep代码只需要运行一次.

再查看一下这个两个tests的output是一样的, 也就是说明确实是只生成了一个GameState实例:

在不同的测试类中共享上下文

上面讲述了如何在一个测试类中不同的测试里共享代码的方法, 而xUnit也可以让我们在不同的测试类中共享上下文.

在Tests项目里建立 GameStateCollection.cs:

using Xunit;namespace Game.Tests
{[CollectionDefinition("GameState collection")]public class GameStateCollection : ICollectionFixture<GameStateFixture> {}
}

这个类GameStateCollection需要实现ICollectionFixture<T>接口, 但是它没有具体的实现.

它上面的CollectionDefinition属性标签作用是定义了一个Collection名字叫做GameStateCollection.

再建立TestClass1.cs:

using Xunit;
using Xunit.Abstractions;namespace Game.Tests
{[Collection("GameState collection")]public class TestClass1{private readonly GameStateFixture _gameStateFixture;private readonly ITestOutputHelper _output;public TestClass1(GameStateFixture gameStateFixture, ITestOutputHelper output){_gameStateFixture = gameStateFixture;_output = output;}[Fact]public void Test1(){_output.WriteLine($"GameState ID={_gameStateFixture.State.Id}");}[Fact]public void Test2(){_output.WriteLine($"GameState ID={_gameStateFixture.State.Id}");}}
}

和TestClass2.cs:

using Xunit;
using Xunit.Abstractions;namespace Game.Tests
{[Collection("GameState collection")]public class TestClass2{private readonly GameStateFixture _gameStateFixture;private readonly ITestOutputHelper _output;public TestClass2(GameStateFixture gameStateFixture, ITestOutputHelper output){_gameStateFixture = gameStateFixture;_output = output;}[Fact]public void Test3(){_output.WriteLine($"GameState ID={_gameStateFixture.State.Id}");}[Fact]public void Test4(){_output.WriteLine($"GameState ID={_gameStateFixture.State.Id}");}}
}

TestClass1和TestClass2在类的上面使用Collection属性标签来调用名为GameState collection的Collection. 而不需要实现任何接口.

这样, xUnit在运行测试之前会建立一个GameState实例共享与TestClass1和TestClass2.

Build, 同时运行TestClass1和TestClass2的Tests:

运行的时间为3秒多:

查看这4个test的output, 可以看到它们使用的是同一个GameState实例:

这一部分先到这, 还剩下最后一部分了.

下面是我的关于ASP.NET Core Web API相关技术的公众号--草根专栏:

使用xUnit为.net core程序进行单元测试(3)相关推荐

  1. 使用xUnit为.net core程序进行单元测试(中)

    第一部分:  使用xUnit为.net core程序进行单元测试(上), 下面有一点点内容是重叠的.... String Assert 测试string是否相等: [Fact] public void ...

  2. 好代码是管出来的——.Net Core中的单元测试与代码覆盖率

    测试对于软件来说,是保证其质量的一个重要过程,而测试又分为很多种,单元测试.集成测试.系统测试.压力测试等等,不同的测试的测试粒度和测试目标也不同,如单元测试关注每一行代码,集成测试关注的是多个模块是 ...

  3. 使用VS Code 开发.NET CORE 程序指南

    1. 前言 近两年来,很多前端的同学都开始将 VSCode 作为前端主力开发工具,其丰富的扩展给程序开发尤其是前端开发带来了很多便利,但是作为微软主力语言的 .NET,却由于有宇宙第一IDE Visu ...

  4. 使用Azure DevOps Pipeline实现.Net Core程序的CD

    上一次我们讲了使用Azure DevOps Pipeline实现.Net Core程序的CI.这次我们来演示下如何使用Azure DevOps实现.Net Core程序的CD. 实现本次目标我们除了A ...

  5. 使用Azure DevOps Pipeline实现.Net Core程序的CI

    上次介绍了Azure Application Insights,实现了.net core程序的监控功能.这次让我们来看看Azure DevOps Pipeline功能.Azure DevOps Pip ...

  6. junit5_使用JUnit对ADF应用程序进行单元测试

    junit5 JUnit是Java语言的单元测试软件包,由于ADF构建在J2EE框架之上,因此可以用来测试Oracle ADF应用程序. 单元测试基本上是根据某些定义的测试标准来验证最小的可测试模块的 ...

  7. 以Windows服务方式运行.NET Core程序

    原文:以Windows服务方式运行.NET Core程序 在之前一篇博客<以Windows服务方式运行ASP.NET Core程序>中我讲述了如何把ASP.NET Core程序作为Wind ...

  8. .NET Core程序瘦身器发布,压缩程序尺寸到1/3

    .NET Core具有[剪裁未使用的代码]的功能,但是由于它是使用静态分析来实现的,因此它的剪裁效果并不是最优的.它有如下两个缺点: 不支持Windows Forms和WPF,而对于程序剪裁功能需求最 ...

  9. 如何优雅的利用Windows服务来部署ASP.NET Core程序

    上一篇文章中我给大家讲述了五种部署ASP.NET Core网站的方法,其中有一种方式是通过Windows服务来进行部署,这样既可以做到开启自启动,又不会因为iis的反向代理而损失部分性能.但是美中不足 ...

最新文章

  1. 响应式开发一招致胜 学习视频 分享
  2. FineUI(开源版)v4.2.2发布(8年125个版本,官网示例突破300个)!
  3. IE滤镜实现透明度/阴影/渐变等特效
  4. Java IO的RandomAccessFile的使用(转)
  5. pxc mysql mycat_Mycat+Pxc的配置
  6. 华人微型计算机之父,计算机之父是谁?
  7. psql 时间日期操作符和函数
  8. Summary - 2017
  9. VM虚拟机Linux克隆后网卡的相关操作
  10. Android加载自定义字体出错,盘点Android使用自定义字体遇到的坑
  11. 带你了解关系网络在反欺诈领域的常见应用
  12. 超大流量分布式系统架构解决方案
  13. 清华月赛 大吉大利晚上吃鸡题解
  14. 关于Excel显示“文件已损坏,无法打开”的解决办法
  15. 什么是深度卷积神经网络,基于深度卷积神经网络
  16. MPU6050 6轴姿态传感器的分析与使用(一)
  17. 计算机和局域网络的保密管理,浅析计算机局域网的安全保密与管理.doc
  18. 建筑公司设计公司网站建设制作费用大概多少
  19. lol服务器什么时候维护,lol等短时间维护是什么?lol11月23日服务器维护详情介绍...
  20. 网络布线与进制转换(详解)

热门文章

  1. eazy ui 复选框单选_UI备忘单:单选按钮,复选框和其他选择器
  2. 游戏安全资讯精选 2017年第十期 英国彩票网遭遇DDoS攻击,中断90分钟 DNSMASQ多高危漏洞公告 阿里云协助警方破获国内最大黑客攻击案,攻击峰值690G...
  3. 题目1362:左旋转字符串(Move!Move!!Move!!!)
  4. 紧急通知:360 网站卫士前端公共库已停止服务
  5. freemarker 异常处理
  6. 数据切分——Atlas介绍
  7. 合理支配“财富”:经理人运用时间的12种典型模式
  8. WordCount--统计输入文件的字符数、行数、单词数(java)--初级功能
  9. nodejs 实践:express 最佳实践(六) express 自省获得所有的路由
  10. C#网络编程(订立协议和发送文件) - Part.4