user2837167
user2837167

Reputation: 231

Execute code before start of method

I have a set of code that i execute in all my test methods, like the login code. Is it possible to minimize that lines of code and ensure it is run before the test method runs, like attributing the method. if we take it as some attribute, then it should also take parameters, wondering how is this achievable. Plmk.

Upvotes: 0

Views: 58

Answers (1)

parishodak
parishodak

Reputation: 4666

In all the unit test frameworks, there is a feature to execute common code before and after tests. Below shows an example of NUnit:

[TestFixture]
public class TestFixtureLifetime
{
    [SetUp]
    public void BeforeTest()
    { Console.WriteLine("BeforeTest"); }

    [TearDown]
    public void AfterTest()
    { Console.WriteLine("AfterTest"); }

    [Test]
    public void Test1()
    { Console.WriteLine("Test1"); }

    [Test]
    public void Test2()
    { Console.WriteLine("Test2"); }
}

When this class is ran, we get the following output: .

BeforeTest
Test1
AfterTest
BeforeTest
Test2
AfterTest

Also,[Setup] and [Teardown] methods are optional. We can mix and match their presence based on requirement.

Upvotes: 1

Related Questions