简体   繁体   中英

How to make a Unit test with several data sources?

I have a method and I want to test it with two data sources (two lists in my case). Can someone help and explain how to make it right? Should I use attribute TestCaseSource and how?

 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"
    };

First, you need your data sources to be static. That is an NUnit 3 requirement.

Once you do that, you can use the ValueSource attribute on each of your parameters. For example,

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

The Sequential attribute specifies that you want NUnit to generate test cases by selecting the values in order. The other options are Combinatorial that causes every combination of values which is the default or Pairwise which just creates cases for all possible pairs.

In your case though, I would recommend merging your two data sources into one and using the TestCaseSource attribute .

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

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

Note that I am using the nameof() operator for C# 6. If you are not using Visual Studio 2015, just switch to strings.

I can't seem to get code into comments on this site, so I'm posting this as a separate answer even though it's really a comment on Rob's answer.

In your particular case, you don't need TestCaseSource at all... Consider this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM