问题描述
TL;DR - 我正在寻找 xUnit 的 MSTest 的 AssemblyInitialize
等效项(也就是我喜欢的 ONE 功能).
TL;DR - I'm looking for xUnit's equivalent of MSTest's AssemblyInitialize
(aka the ONE feature it has that I like).
特别是我正在寻找它,因为我有一些 Selenium 烟雾测试,我希望能够在没有其他依赖项的情况下运行它们.我有一个 Fixture 将为我启动 IisExpress 并在处置时将其杀死.但是在每次测试之前这样做会极大地膨胀运行时.
Specifically I'm looking for it because I have some Selenium smoke tests which I would like to be able to run with no other dependencies. I have a Fixture that will launch IisExpress for me and kill it on disposal. But doing this before every test hugely bloats runtime.
我想在测试开始时触发此代码一次,并在最后处理它(关闭进程).我怎么能这样做呢?
I would like to trigger this code once at the start of testing, and dispose of it (shutting down the process) at the end. How could I go about doing that?
即使我能够以编程方式访问诸如当前正在运行多少测试"之类的内容,我也能弄清楚.
Even if I can get programmatic access to something like "how many tests are currently being run" I can figure something out.
推荐答案
截至 2015 年 11 月,xUnit 2 已经发布,因此有一种规范的方式可以在测试之间共享功能.这里记录了它.
As of Nov 2015 xUnit 2 is out, so there is a canonical way to share features between tests. It is documented here.
基本上你需要创建一个类来做fixture:
Basically you'll need to create a class doing the 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
属性的虚拟类.此类允许 Xunit 创建一个测试集合,并将给定的夹具用于该集合的所有测试类.
A dummy class bearing the CollectionDefinition
attribute.
This class allows Xunit to create a test collection, and will use the given fixture for all test classes of the collection.
[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.
}
然后您需要在所有测试类中添加集合名称.测试类可以通过构造函数接收fixture.
Then you need to add the collection name over all your test classes. The test classes can receive the fixture through the constructor.
[Collection("Database collection")]
public class DatabaseTestClass1
{
DatabaseFixture fixture;
public DatabaseTestClass1(DatabaseFixture fixture)
{
this.fixture = fixture;
}
}
它比 MsTests AssemblyInitialize
更冗长,因为你必须在每个测试类上声明它属于哪个测试集合,但它也更可模块化(并且使用 MsTests 你仍然需要放置一个 TestClass你的课)
It's a bit more verbose than MsTests AssemblyInitialize
since you have to declare on each test class which test collection it belongs, but it's also more modulable (and with MsTests you still need to put a TestClass on your classes)
注意:样本取自 文档.
这篇关于在 xUnit.net 中的所有测试之前和之后运行一次代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!