unit testingC#

我是unit testingC#Web API控制器 – 每个都需要几个参数来初始化。 我现在在每个测试中都有这个代码,但它非常笨重。 如何将此代码放入[TestInitialize]以便在每次测试之前运行?

我尝试了以下但显然它超出了测试方法的范围。

[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方法中初始化它们。

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

这样,可以从每次测试访问字段