簡體   English   中英

如何使用多個數據源進行單元測試?

[英]How to make a Unit test with several data sources?

我有一個方法,我想用兩個數據源(以我的情況為兩個列表)進行測試。 有人可以幫忙解釋一下如何做對嗎? 我應該使用屬性TestCaseSource以及如何使用嗎?

 public void TestMethodIntToBin(int intToConvert, string result)
    {
        Binary converter = new Binary();
        string expectedResult = converter.ConvertTo(intToConvert);
        Assert.AreEqual(expectedResult, result);
    }

public List<int> ToConvert = new List<int>()
    {
        12,
        13,
        4,
        64,
        35,
        76,
        31,
        84
    };
    public List<string> ResultList = new List<string>()
    {
        "00110110",
        "00110110",
        "00121011",
        "00110110",
        "00110110",
        "00100110",
        "00110110",
        "00110110"
    };

首先,您需要數據源是靜態的。 那是NUnit 3的要求。

完成后,可以在每個參數上使用ValueSource屬性 例如,

[Test, Sequential]
public void TestMethodIntToBin([ValueSource(nameof(ToConvert))] int intToConvert, 
                               [ValueSource(nameof(ResultList))] string result)
{
    // Asserts
}

Sequential屬性指定您希望NUnit通過按順序選擇值來生成測試用例。 其他選項是Combinatorial(組合) ,它導致值的每種組合(默認值)或Pairwise(成對) ,僅為所有可能的對創建個案。

不過,根據您的情況,我建議將您的兩個數據源合並為一個,並使用TestCaseSource屬性

[TestCaseSource(nameof(Conversions))]
public void TestMethodIntToBin(int intToConvert, string result)
{
    // Asserts
}

static object[] Conversions = {
    new object[] { 12, "00110110" },
    new object[] { 13, "00110110" }
}

請注意,我正在為C#6使用nameof()運算符。如果您沒有使用Visual Studio 2015,則只需切換到字符串即可。

我似乎無法在該站點的注釋中添加代碼,因此即使它實際上是對Rob答案的注釋,我也將其作為單獨的答案發布。

在您的特定情況下,您根本不需要TestCaseSource ...請考慮以下事項:

[TestCase( 12, "00110110" )]
[TestCase( 13, "00110110" )]
public void TestMethodIntToBin(int intToConvert, string result)
{
    // Asserts
}

暫無
暫無

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

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