Reputation: 829
Is there any possibility to define a method with Nunit, that would execute before each test in the assembly?
To be perfectly clear: I do NOT want to execute some code once before all tests, but I need to do some general setup before each test. So if i have 10 tests, I want my method to be executed 10 times.
Inheritance is sadly not an option to me (I already use it for a different purpose and cannot mix)
Upvotes: 20
Views: 19681
Reputation: 13736
You can define an Action Attribute that contains the desired code in its Before method. Apply it to the assembly with an argument indicating it should be used for every test.
Note that Action Attribute works a bit differently between NUnit 2 and 3, so be sure to check the appropriate level of the docs.
Upvotes: 13
Reputation: 15982
You can setup a method using SetupAttribute
that will be executed before each tests in a TextFixture
class, but only there.
Something like this:
[TestFixture]
class SomeTests
{
[SetUp]
public void SetupBeforeEachTest()
{
//Some code
}
}
I know you say you can't use inheritance, but if you want to execute a method before each test in the assembly, I think this is the best way since the SetUp
attribute is inherited from any base class. Therefore, if a base class has defined a SetUp
method, that method will be called before each test method in the derived class:
abstract class BaseTestFixture
{
[SetUp]
public void SetupBeforeEachTest()
{
//Some code
}
}
[TestFixture]
class SomeTests : BaseTestFixure
{
//Tests
}
Upvotes: 15