XUnit - Shared Context between Tests
单元测试类通常都会有share setup和cleanup的相关代码。xUnit.net根据共享的范围提供了几种share setup和cleanup的方法。
- Constructor and Dispose (shared setup/cleanup code 无共享对象实例)
- Class Fixtures (一个类中的多个test共享一个对象实例)
- Collection Fixtures (多个类共享对象实例)
Constructor and Dispose
使用场景: 当你想在每次测试后clean测试上下文 (shared setup/cleanup code 无共享对象实例)。
每次测试运行时xUnit.net会创建测试类的实例,所以测试类构造函数里的代码每次测试时都会运行。因此如果你想有些想可复用的上下文,构造函数是个非常适合放置这些可复用上下文的地方。
如果你想cleanup上下文,只需让你的测试类实现IDisposable, 并将cleanup上下文的代码写在Dispose() 方法中即可。
例子:
public class StackTests : IDisposable
{
Stack<int> stack;
public StackTests()
{
stack = new Stack<int>();
}
public void Dispose()
{
stack.Dispose();
}
[Fact]
public void WithNoItems_CountShouldReturnZero()
{
var count = stack.Count;
Assert.Equal(0, count);
}
[Fact]
public void AfterPushingItem_CountShouldReturnOne()
{
stack.Push(42);
var count = stack.Count;
Assert.Equal(1, count);
}
}
有时候将上面的结构称为 "test class as context" 模式, 因为测试类本身自包含了setup上下文和cleanup上下文的代码。你甚至可以根据setup上下文后的情况来命名你的测试类,这样可以更容易的看出这个测试类的初始点是什么样的:
public class StackTests
{
public class EmptyStack
{
Stack<int> stack;
public EmptyStack()
{
stack = new Stack<int>();
}
// ... tests for an empty stack ...
}
public class SingleItemStack
{
Stack<int> stack;
public SingleItemStack()
{
stack = new Stack<int>();
stack.Push(42);
}
// ... tests for a single-item stack ...
}
}
因为每个context是处于某种情况的Stack。我们把EmptyStack和SingleItemStack类放在StackTests类里面。
Class Fixtures
使用场景: 你想创建一个测试上下文对象并在一个测试类中的多个测试方法中共享它,并在这个类中打得所有的测试结束后cleanup它。
有的时候setup和cleanup上下文是非常耗时的。如果你每个测试都去setup和cleanup上下文,那会非常耗时。这时你可以使用xUnit.net提供的fixture特性用来在一个测试类中的所有测试方法中共享同一个上下文对象。
我们已经知道 xUnit.net会为每次测试创建一个测试类的实例。当我们使用class fixture时, xUnit.net会确保在任何test测试前先创建fixture实例,并且一旦测试全部完成会调用Dispose执行cleanup。
使用class fixture步骤如下:
- 创建fixture class, 将startup代码放在fixture class的构造函数中。
- 如果fixture class要执行cleanup,那么需要实现
IDisposable, 并在Dispose()中写cleanup的代码。 - 测试类需要实现
IClassFixture<> - 如果测试类想获取fixture class的实例,只需将fixture类作为参数传到测试类的构造函数中即可。
例子:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... 在测试数据库中初始化数据 ...
}
public void Dispose()
{
// ... 清除测试数据 ...
}
public SqlConnection Db { get; private set; }
}
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
DatabaseFixture fixture;
public MyDatabaseTests(DatabaseFixture fixture)
{
this.fixture = fixture;
}
// ... write tests, using fixture.Db to get access to the SQL Server ...
}
在MyDatabaseTests的测试运行前, xUnit.net会创建一个DatabaseFixture的实例。每个测试都会创建一个MyDatabaseTests的实例, 并将共享的DatabaseFixture实例传到测试类的构造函数中去。
注意: 如果你只在没有实现IClassFixture<>的情况下将fixture class做为了测试类的构造函数参数, xUnit.net会报错。
如果你需要多个fixture对象,只要实现多个IClassFixture<>,并将这些fixture对象作为测试类的构造函数参数就行了。构造函数参数的顺序不重要。
注意你没法控制fixture对象创建的顺序,fixture不能依赖其他的fixture。如果你想控制顺序或者在fixture之间有依赖关系,你需要创建一个类并在其中封装另外两个fixture。
注意: Fixtures必须和使用它的测试类在同一个程序集。
Collection Fixtures
使用场景: 你想在多个测试类中共享一个测试上下文对象,并在所有测试类的测试都跑完了后执行cleanup。
使用collection fixtures步骤如下:
- 创建fixture class, 将startup代码放在fixture class的构造函数中。
- 如果fixture class要执行cleanup,fixture class需要实现
IDisposable, 将cleanup代码放在Dispose()方法中。 - 创建collection definition class, 且添加
[CollectionDefinition]attribute, 给一个唯一的名。 - collection definition class实现
ICollectionFixture<>。 - 为所有要用collection fixtures的测试类添加
[Collection]attribute, 并使用在collection definition class的[CollectionDefinition]attribute的唯一名。 - 如果测试类想获取fixture class的实例,只需将fixture类作为参数传到测试类的构造函数中即可。
例子:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
[Collection("Database collection")]
public class DatabaseTestClass1
{
DatabaseFixture fixture;
public DatabaseTestClass1(DatabaseFixture fixture)
{
this.fixture = fixture;
}
}
[Collection("Database collection")]
public class DatabaseTestClass2
{
// ...
}
xUnit.net对collection fixtures的处理可class fixtures类似, 除了collection fixture对象的生命周期更长: 在所有测试类的测试前创建,在所有测试类的测试完成后cleanup。
Test collections can also be decorated with IClassFixture<>. xUnit.net treats this as though each individual test class in the test collection were decorated with the class fixture.
Test collections also influence the way xUnit.net runs tests when running them in parallel. For more information, see Running Tests in Parallel.
注意: Fixtures和使用它的测试类必须在同一个程序集。
XUnit - Shared Context between Tests的更多相关文章
- Selenium + Chrome headless 报ERROR:gpu_process_transport_factory.cc(1007)] Lost UI shared context 可忽略并配置不输出日志
Selenium不再推荐使用PhantomJS,会报如下警告 UserWarning: Selenium support for PhantomJS has been deprecated, plea ...
- 体验 ASP.NET Core 集成测试三剑客:xUnit.net、TestServer、EF Core InMemory
这是昨天解决的一个问题,针对一个 web api 的客户端代理类写集成测试,既要测试 web api,又要测试 web api 客户端. 测试 web api,就要在运行测试时自动启动 web api ...
- setup in xunit
https://xunit.github.io/docs/shared-context Shared Context between Tests It is common for unit test ...
- 单元测试过多,导致The configured user limit (128) on the number of inotify instances has been reached.
最近在一个asp.net core web项目中使用TDD的方式开发,结果单元测试超过128个之后,在CI中报错了:"The configured user limit (128) on t ...
- Xunit
Attributes Note: This table was written back when xUnit.net 1.0 has shipped, and needs to be updated ...
- XUnit 依赖注入
XUnit 依赖注入 Intro 现在的开发中越来越看重依赖注入的思想,微软的 Asp.Net Core 框架更是天然集成了依赖注入,那么在单元测试中如何使用依赖注入呢? 本文主要介绍如何通过 XUn ...
- xUnit随笔
XUnit入门 1.如果之前安装了xUnit.net Visual Studio Runner扩展包,通过"工具"菜单下的"扩展和更新"先将该扩展包卸载. 2. ...
- 使用 xunit 编写测试代码
使用 xunit 编写测试代码 Intro xunit 是 .NET 里使用非常广泛的一个测试框架,有很多测试项目都是在使用 xunit 作为测试框架,不仅仅有很多开源项目在使用,很多微软的项目也在使 ...
- 使用xUnit为.net core程序进行单元测试(3)
第1部分: http://www.cnblogs.com/cgzl/p/8283610.html 第2部分: http://www.cnblogs.com/cgzl/p/8287588.html 请使 ...
随机推荐
- 严重: Exception loading sessions from persistent storage Java.io.EOFException
tomcat启动时报此异常,但web页均能正常运行:对程序影响不大. /*具体原因时tomcat--work--(你当前运行的工程名)--session.ser*/删除即可解决 分析: EOFExce ...
- 理解Java对象序列化
http://www.blogjava.net/jiangshachina/archive/2012/02/13/369898.html 1. 什么是Java对象序列化 Java平台允许我们在内存中创 ...
- android socket 线程连接openwrt与arduino单片机串口双向通信
package zcd.netanything; import java.io.BufferedReader; import java.io.InputStreamReader; import jav ...
- windows10的第一天使用总结
一.快速开机设置 我的电脑配置如图,装有VS2015 2010 OFFICE等常用开发工具,在线升级后开机速度并没有明显提升. 1.保证windows font cache service服务启动,3 ...
- MySQL 主从复制与读写分离概念及架构分析
1.MySQL主从复制入门 首先,我们看一个图: 影响MySQL-A数据库的操作,在数据库执行后,都会写入本地的日志系统A中. 假设,实时的将变化了的日志系统中的数据库事件操作,在MYSQL-A的33 ...
- Openjudge 1.13-23:区间内的真素数(每日一水)
总时间限制: 1000ms 内存限制: 65536kB 描述 找出正整数 M 和 N 之间(N 不小于 M)的所有真素数.真素数的定义:如果一个正整数 P 为素数,且其反序也为素数,那么 P 就为 ...
- [LeetCode] Optimal Account Balancing 最优账户平衡
A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...
- [LeetCode] Integer to Roman 整数转化成罗马数字
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 t ...
- 学券制(教育券、school voucher)
美国「学券制」是怎样的一种制度?它为什么是共和党的执政政策?它在美国及其它地区有实施吗?效果如何?能否在保证公平的同时,通过市场提高教育质量? 作者:冉筱韬链接:https://www.zhihu.c ...
- Beta版本冲刺计划及安排
经过紧张的Alpha阶段,很多组已经从完全不熟悉语言和环境,到现在能够实现初步的功能.下一阶段即将加快编码进度,完成系统功能.强化软件工程的体会.Beta阶段的冲刺时间为期七天,安排在2016.12. ...