One Time initialization for Nunit
Clash Royale CLAN TAG#URR8PPP
One Time initialization for Nunit
Where should I place code that should only run once (and not once per class)? An example for this would be a statement that initializes the DB connection string. And I only need to run that once and I don't want to place a new method within each "TestFixture" class just to do that.
3 Answers
3
The [SetUpFixture]
attribute allows you to run setup and/or teardown code once for all tests under the same namespace.
[SetUpFixture]
Here are the docs on SetUpFixture
. According to the docs:
SetUpFixture
A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly.
So if you need SetUp
and TearDown
for all tests, then just make sure the SetUpFixture
class is not in a namespace.
SetUp
TearDown
SetUpFixture
Alternatively, you could always define a static class strictly for the purpose of defining “global” test variables.
According to the NUnit docs: "A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly." So if you need SetUp and TearDown for all tests, then just make sure the SetUpFixture class is not in a namespace.
– Justin Holzer
Jun 12 '14 at 18:58
These are the updated docs for the SetupFixture attribute for NUnit 3+: github.com/nunit/docs/wiki/SetUpFixture-Attribute The big change is that you must use the [OneTimeSetup] and [OneTimeTearDown] attributes on the actual methods, instead of just [SetUp] and [TearDown].
– Jeffrey Harmon
Dec 14 '16 at 13:09
Create a class (I call mine Config) and decorate it with the [SetUpFixture]
attribute. The [SetUp]
and [TearDown]
methods in the class will run once.
[SetUpFixture]
[SetUp]
[TearDown]
[SetUpFixture]
public class Config
[SetUp] // [OneTimeSetUp] for NUnit 3.0 and up; see http://bartwullems.blogspot.com/2015/12/upgrading-to-nunit-30-onetimesetup.html
public void SetUp()
[TearDown] // [OneTimeTearDown] for NUnit 3.0 and up
public void TearDown()
NUnit v3 changes the attributes slightly. see v3 docs
– Dave Turvey
Jan 5 '16 at 9:56
NUnit 3:
[SetUpFixture]
public class TestLogging
[OneTimeSetUpAttribute]
public void Setup()
DoStuff();
The name can also be simplified to
[OneTimeSetUp]
.– SharpC
Dec 19 '16 at 9:36
[OneTimeSetUp]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
that is exactly what I was looking for, thanks :)
– code-ninja
Jul 9 '10 at 0:46