Reputation: 1081
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();
}
Upvotes: 60
Views: 98490
Reputation: 1480
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
Upvotes: 103