0

i am writing Data driven unit tests in C#. I want to attach data source at class level so that all the test will run for set of inputs. Some how the problem is with the TestContext property which i cannot access as the ClassInitialize method is static. Below is the code -

    [ClassInitialize]
            [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
                "TrackingData.csv",
                "TrackingData#csv",
                DataAccessMethod.Sequential)]
            public static void ClassInit(TestContext tc)
    {
       // Inside this i am trying to access the static TestContext property but its not working
    }

public static TestContext TestContext {get; set;}

The error which i am getting is 'you cannot have a static TestContext Property.

Could some one please help me out here?

Jash
  • 942
  • 4
  • 17
  • 40

1 Answers1

1

TestContext has to be an instance property, it cannot be static. I'm afraid you have no other option than duplicating the attribute for each TestMethod.

One thing you could do, is to move the description of your data source to the config file as explained here.

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • Thanks for the reply! Actually after reading a single row from csv file i need to perform couple of operation. And this will set some values which should be common for every test in that run. So i need to read one row set some values and test will run taking all those values as input. Then for the next row the same process should repeat. If i move the code in TestMethod which will be more than 100 eventually then i am doing two things wrong - repeating the same attribute and running the common operation each time. Is there any other way to achieve this ? – Jash Jun 06 '13 at 16:11
  • if i will read the CSV file (not excel) manually in class initialize, then how will i run the test again and again repeatedly ? This actually works automatically with Data Driven tests, how can i do this manually ? – Jash Jun 06 '13 at 16:21
  • True, I don't think there's an easy way to avoid the repetition – vc 74 Jun 06 '13 at 16:28
  • One last thing - Can i attach the Data Source attribute at Testintialize() and make it work for all test method? I am facing issue even this - the DataRow property for TestContext is null in this case whereas it works fine when the data source attribute is attached to each test method – Jash Jun 06 '13 at 16:48
  • you have provided the link fo using app.config, what will be the connection string in case of CSV file ? – Jash Jun 06 '13 at 17:17
  • why dont you create a base class and inherit unittest from base? – Nick Kahn Dec 09 '13 at 15:49