[英]Unit Test C# [TestInitialize]
I am performing Unit Tests on C# Web API controllers - and each one requires several parameters to initialize.我正在 C# Web API 控制器上执行单元测试 - 每个控制器都需要几个参数来初始化。 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?如何将此代码放入 [TestInitialize] 以便它在每次测试之前运行?
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();
}
You can set the variables that you need as fields of the test class and then initialize them in the TestInitialize method.您可以将需要的变量设置为测试类的字段,然后在 TestInitialize 方法中对其进行初始化。
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这样可以从每个测试访问字段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.