Is it possible to have a [OneTimeSetup] for ALL tests?

旧时模样 提交于 2021-01-20 16:34:37

问题


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();
    }
}

NavigationTests

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

MainPageTests

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

回答1:


OneTimeSetUpAttribute has two uses.

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.

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.

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.

For more info about SetUpFixture, see the docs.



来源:https://stackoverflow.com/questions/42213167/is-it-possible-to-have-a-onetimesetup-for-all-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!