unit-testing - 如何从外部类运行 OneTimeSetUp 和 OneTimeTearDown
问题描述
你好,我有几个测试类,我使用的资源与我OneTimeSetUp
和OneTimeTearDown
哪个是相同的IEmbeddable
。
假设我有N
要重用的测试类OneTimeSetUp
和OneTimeSetDown
资源(接口IEmbeddedable
)。如何创建一个EmbeddableController
可以被所有测试类重用的静态类?
基本上我想:
-Start static Resource of type `IEmbeddedable` once
-Run TestClass 1 on resource ( set it up +tear it down)
-Run TestClass 2 on resource (set it up + tear it down)
......
-Run TestClass N on resource (set it up +tear it down)
嵌入式
interface IEmbeddedable:IDisposable {
int ExposedPort { get; }
}
Test_ClassX
class Test_ClassX {
private IEmbeddedable server;
[OneTimeSetUp]
public void Launch() {
server = RedisServer.Launch();
}
[OneTimeTearDown]
public void Stop() {
this.server.Dispose();
}
[TestCase()]
public async Task CanRunEmbeddedServer() {
using (server) {
var multi = new Multiplexer();
using (var link = multi.OpenLink(Address.Create(Port:server.ExposedPort))) {
string rez=await link.FlushAllAsync();
Assert.AreEqual(rez, "OK");
}
}
}
}
原型
static class EmbeddedController {
private static IEmbeddedable server;
[OneTimeSetUp]
public static void Run() {
server = RedisServer.Launch();
}
public static void Stop() {
server.Dispose();
}
}
我如何在所有测试类中注入最后一个类?它可以是静态的,也可以不是静态的,无论哪种方式,它都只是一个实例。
解决方案
OneTimeSetUp
可以在各个级别运行。在 a 上TestFixture
,它为夹具运行一次。在 SetUpFixture 上,它为命名空间运行一次。这为您提供了多种选择...
让你所有的装置都继承自
EmbeddedController
. 但是,OneTimeSetUp
将为每个夹具运行一次。虽然可以进行一次测试并且只初始化一次服务器,但您将无法知道最后一次测试何时运行,以便您可以处理它。我的结论是,这不适用于您的情况,尽管它适用于任何没有资源且不需要处置的东西。将所有需要的固定装置放在
EmbeddedController
同一个命名空间中,没有任何其他类。放入EmbeddedController
相同的命名空间并使其成为SetUpFixture
.OneTimeSetUp
will 在任何灯具之前运行一次,而willOneTimeTearDown
在所有灯具完成后运行一次。为了让灯具访问服务器,您应该创建Server
一个EmbeddedController
.
推荐阅读
- jwt - 具有多个 JWKS 解析器的单一计划
- azure - Azure 成本导出应用什么业务逻辑?
- php - Laravel 8 不发送验证邮件
- ruby-on-rails - 如何在按钮单击时显示 Ruby Rails Form Modal 弹出窗口?
- flutter - Dart 双精度混淆
- git - Git push to master 领先一个提交
- swift - 如何防止在 NSOutlineView 中右键单击文本字段重命名
- c# - 根据 orderid 保存单独的单独 xml 文件
- packer - 使用打包器时,如何跳过构建器并直接进入配置器或后处理器阶段?
- javascript - 尝试在 mongoDB 上实现搜索并让结果显示在页面上