我是单元测试C#Web API控制器 - 每个都需要几个参数来初始化。我目前在每个测试中都有这个代码,但它非常笨重。如何将此代码放入[TestInitialize]以便它在每次测试之前运行?
我尝试了以下内容,但显然它超出了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();
}
由于
答案 0 :(得分:59)
您可以将所需的变量设置为测试类的字段,然后在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();
}
}
这样可以从每个测试中访问字段