是否可以为所有测试使用 [OneTimeSetup]? [英] Is it possible to have a [OneTimeSetup] for ALL tests?

查看:44
本文介绍了是否可以为所有测试使用 [OneTimeSetup]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NUnit 运行一些 Selenium 测试,但我遇到了一个小问题,我想看看我是否可以得到纠正.发生的情况是 [OneTimeSetUp][OneTimeTearDown] 在每个装置完成后运行.我想要的是在测试开始时运行一次 [OneTimeSetUp],并在所有装置完成后运行拆卸.

I'm using NUnit to run some Selenium tests and I've got a minor issue I want to see if I can get corrected. What's happening is that the [OneTimeSetUp] and [OneTimeTearDown] is running after each fixture finishes. What I want is to run [OneTimeSetUp] once when the tests are started, and the teardown to run once ALL fixtures have finished.

TestBaseClass.cs

public class TestBaseClass
{

    [OneTimeSetUp]
    public void Init()
    {
         // Login
    }

    [OneTimeTearDown]
    public void TearDown()
    {
        Driver.Close();
    }
}

导航测试

[TestFixture]
public class NavigationTests : TestBaseClass
{
    // Tests
}

MainPageTests

[TestFixture]
public class MainPageTests : TestBaseClass
{
    // Tests
}

推荐答案

OneTimeSetUpAttribute 有两个用途.

OneTimeSetUpAttribute has two uses.

首先,它标记测试装置中的一个方法,该方法在该固定装置中的任何其他测试之前运行一次.这就是您通过从基类继承来使用它的方式.由于继承,OneTimeSetUp 出现在每个派生的装置中,但它仍然运行多次,每个装置一次.

In the first, it marks a method in a test fixture that is run once before any other tests in that fixtrue. That's how you are using it, by inheriting from a base class. The OneTimeSetUp appears, thanks to inheritance, in each of your derived fixtures but it is still run multiple times, once for each fixture.

第二种用途是在 SetUpFixture 中.如果您在特定命名空间中创建 SetUpFixture,它的 OneTimeSetUp 方法将在该命名空间中的任何其他测试之前运行一次.如果您在任何命名空间之外创建 SetUpFixture,那么它的 OneTimeSetUp 将在程序集中的任何测试之前运行一次.

The second use is in a SetUpFixture. If you create a SetUpFixture in a particular namespace, it's OneTimeSetUp method will run once, before any other tests in that namespace. If you create the SetUpFixture outside of any namespace, then its OneTimeSetUp will run once before any tests in the assembly.

更新:有人建议最后一句应该说在包含 TestFixture 的任何命名空间之外".那实际上是不正确的.SetUpFixture必须在任何命名空间之外才能在程序集级别运行.如果有一个顶级命名空间,其中包含所有测试代码,那么您也可以在那里放置一个 SetUpFixture,效果大致相同.但是,如果它位于一个名称空间中,在其下没有测试,那么它将永远不会运行.

UPDATE: Someone suggested that the last sentence should say "outside of any namespace that contains a TestFixture." That would actually be incorrect. The SetUpFixture must be outside of any namespace to function at the assembly level. If there is a top-level namespace, which contains all test code, then you may also place a SetUpFixture there, with approximately the same effect. But if it's in a namespace with no tests under it, then it will never be run.

有关 SetUpFixture 的更多信息,请参阅文档.

For more info about SetUpFixture, see the docs.

这篇关于是否可以为所有测试使用 [OneTimeSetup]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆