簡體   English   中英

單元測試 C# [TestInitialize]

[英]Unit Test C# [TestInitialize]

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

您可以將需要的變量設置為測試類的字段,然后在 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();
    }   
}

這樣可以從每個測試訪問字段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM