MSTest - DataTestMethod 中参数的默认值

我正在尝试对 DataTestMethod 中的参数使用默认值。我有以下代码:


[DataTestMethod]            

[DataRow("sampleString", true)]

[DataRow("sampleString2")]            

public async Task SampleTest(string parameterA, bool parameterB = false)

{

    var condition = await AsyncOperation();


    Assert.AreEqual(parameterB, condition);

}

但是,我得到: System.Reflection.TargetParameterCountException: Parameter count mismatch.


有没有办法为方法参数定义默认值并跳过在 DataRow 中说明它?


慕的地10843
浏览 124回答 1
1回答

眼眸繁星

最简单的方法是编写自己的 DataRowAttribute。如果你看看这个答案,关于检查方法中的默认参数:https : //stackoverflow.com/a/20759946/7225096,那么你可以写这样的东西:public class MyDataRowAttribute : DataRowAttribute, ITestDataSource{&nbsp; &nbsp; public MyDataRowAttribute(object data1) : base(data1)&nbsp; &nbsp; { }&nbsp; &nbsp; public MyDataRowAttribute(object data1, params object[] moreData) : base(data1, moreData)&nbsp; &nbsp; { }&nbsp; &nbsp; public new IEnumerable<object[]> GetData(MethodInfo methodInfo)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var parameters = methodInfo.GetParameters();&nbsp; &nbsp; &nbsp; &nbsp; object[] args = new object[parameters.Length];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < args.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (i < base.Data.Length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; args[i] = base.Data[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (parameters[i].HasDefaultValue)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; args[i] = parameters[i].DefaultValue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new ArgumentException("Not enough arguments provided");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new List<object[]> { args };&nbsp; &nbsp; }}并像这样使用它:[DataTestMethod][MyDataRow("sampleString", true)][MyDataRow("sampleString2")]public async Task SampleTest(string parameterA, bool parameterB = false){&nbsp; &nbsp; var condition = await AsyncOperation();&nbsp; &nbsp; Assert.AreEqual(parameterB, condition);}
打开App,查看更多内容
随时随地看视频慕课网APP