单元测试C#[TestInitialize] [英] Unit Test C# [TestInitialize]
问题描述
我正在C#Web API控制器上执行单元测试-每个测试都需要几个参数进行初始化.目前,我在每个测试中都有以下代码,但它非常庞大.如何将这段代码放入[TestInitialize]中,使其在每次测试之前运行?
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();
}
推荐答案
您可以将所需的变量设置为测试类的字段,然后在TestInitialize方法中对其进行初始化.
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
这篇关于单元测试C#[TestInitialize]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!