首页 > 解决方案 > 如何从外部类运行 OneTimeSetUp 和 OneTimeTearDown

问题描述

你好,我有几个测试类,我使用的资源与我OneTimeSetUpOneTimeTearDown 哪个是相同的IEmbeddable

假设我有N要重用的测试类OneTimeSetUpOneTimeSetDown资源(接口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();
        }
    }

我如何在所有测试类中注入最后一个类?它可以是静态的,也可以不是静态的,无论哪种方式,它都只是一个实例。

标签: unit-testing.net-corenunit

解决方案


OneTimeSetUp可以在各个级别运行。在 a 上TestFixture,它为夹具运行一次。在 SetUpFixture 上,它为命名空间运行一次。这为您提供了多种选择...

  1. 让你所有的装置都继承自EmbeddedController. 但是,OneTimeSetUp将为每个夹具运行一次。虽然可以进行一次测试并且只初始化一次服务器,但您将无法知道最后一次测试何时运行,以便您可以处理它。我的结论是,这不适用于您的情况,尽管它适用于任何没有资源且不需要处置的东西。

  2. 将所有需要的固定装置放在EmbeddedController同一个命名空间中,没有任何其他类。放入EmbeddedController相同的命名空间并使其成为SetUpFixture. OneTimeSetUpwill 在任何灯具之前运行一次,而willOneTimeTearDown在所有灯具完成后运行一次。为了让灯具访问服务器,您应该创建Server一个EmbeddedController.


推荐阅读