57

I am performing Unit Tests on C# Web API controllers - and each one requires several parameters to initialize. I have the following code in each test at the moment but it's very bulky. How can I put this code into the [TestInitialize] so that it runs before each test?

I have tried the following but obviously it exists out of scope for the testmethods.

[TestInitialize]
public void TestInitialize()
{
    APIContext apicon = new APIContext();
    xRepository xRep = new xRepository(apicon);
    var controller = new relevantController(cRep);
    controller.Request = new HttpRequestMessage();
    controller.Configuration = new HttpConfiguration();
    relevantFactoryModel update = new relevantFactoryModel();
}   
anthonyhumphreys
  • 1,051
  • 2
  • 12
  • 25

1 Answers1

98

You can set the variables that you need as fields of the test class and then initialize them in the TestInitialize method.

class Tests 
{
    // these are needed on every test
    APIContext apicon;
    XRepository xRep;
    Controller controller;
    RelevantFactoryModel update;

    [TestInitialize]
    public void TestInitialize()
    {
        apicon = new APIContext();
        xRep = new xRepository(apicon);
        controller = new relevantController(cRep);
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();
        update = new relevantFactoryModel();
    }   
}

This way the fields can be accessed from every test

dmorganb
  • 1,408
  • 16
  • 26
  • 8
    Tests run in parallel. The method TestInitialize() will be executed before every test that executes. Therefore the fields may be reinitialised while a test is running. True or false ? – Captain Sensible Oct 01 '18 at 08:11
  • 16
    I think that when you run the tests in parallel the runner will create an instance of the TestClass for each Thread, so the fields won't be touched while a test is running – dmorganb Oct 01 '18 at 22:28