How can I pass property as parameter in MSTest Dat

2019-08-03 07:28发布

问题:

I have a DataTestMethod in my unit test using MSTest, and I have a string property in my constructor, let's say I have this code for example:

[DataTestMethod]
[DataRow("test")] 
[DataRow(stringproperty)] // How is this?

public void TestMethod(string test) {
    Assert.AreEqual("test", test);
}

Is it possible to pass a property as parameter in DataRow?

Thanks.

回答1:

Yes if you use the DynamicDataAttribute

[DynamicData("TestMethodInput")]
[DataTestMethod]
public void TestMethod(string test)
{
    Assert.AreEqual("test", test);
}

public static IEnumerable<object[]> TestMethodInput
{
    get
    {
        return new[]
        {
            new object[] { stringproperty },
            new object[] { "test" }
        };
    }
}


回答2:

Try this

private List<string> testData=new List<string>();
testData.Add("test");
testData.Add("test1");

private IEnumerable<object[]> ListOfTestData =>
    new List<string[]> 
    {
        new[] {testData[0]},
        new[] {testData[1]}
    };

[DataTestMethod]
[DynamicData (nameof (ListOfTestData))]
public void TestMethod(string test) 
{
    Assert.AreEqual("test", test);
}