Unit Test C# [TestInitialize]

C#Unit Testingasp.net Web-Api

C# Problem Overview


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();
}   

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanthonyhumphreysView Question on Stackoverflow
Solution 1 - C#dmorganbView Answer on Stackoverflow