【问题标题】:Unit Test C# [TestInitialize]单元测试 C# [TestInitialize]
【发布时间】:2014-10-24 12:36:40
【问题描述】:

我在 C# 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();
}   

【问题讨论】:

    标签: c# unit-testing asp.net-web-api


    【解决方案1】:

    您可以将需要的变量设置为测试类的字段,然后在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();
        }   
    }
    

    这样可以从每个测试中访问字段

    【讨论】:

    • 测试并行运行。 TestInitialize() 方法将在每个测试执行之前执行。因此,可以在测试运行时重新初始化这些字段。是真是假?
    • 我认为当您并行运行测试时,运行器将为每个线程创建一个 TestClass 的实例,因此在测试运行时不会触及字段
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 2010-12-24
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多