[英]C# Unit Test DynamicDataDisplayName using MSTest
我正在使用 MSTest 執行一些單元測試,我了解到我可以使用[DynamicData]
屬性輸入不同的案例進行測試,但我不能使用屬性屬性: DynamicDataDisplayName
為不同的案例設置名稱。
我的測試代碼是:
[TestMethod]
[DynamicData(nameof(TestInputs_BeReady), DynamicDataSourceType.Method,
DynamicDataDisplayName = nameof(GetTestDisplayNames),
DynamicDataDisplayNameDeclaringType = typeof(List<string>))]
public void Should_BeReady(object expValue, object[] inputs)
{
// Arrange
// Act
ui.InputID = (string)inputs[0];
ui.InputName = (string)inputs[1];
ui.InputList = (List<string>)inputs[2];
// Assert
Assert.AreEqual(expValue, onReadyStateChangeArgs.Ready);
}
public static IEnumerable<object[]> TestInputs_BeReady()
{
return new[]
{
new object[] { true, new object[] { "UTSZ0", "Unit Test Size List" , new List<string> { "entry_01", "entry_02" } } },
new object[] { false, new object[] { "STEST", "Unit Test Size List" , new List<string> { "entry_01", "entry_02" } } },
new object[] { false, new object[] { "", "Unit Test Size List" , new List<string> { "entry_01", "entry_02" } } },
new object[] { false, new object[] { "UTSZ0", "" , new List<string> { "entry_01", "entry_02" } } },
new object[] { false, new object[] { "UTSZ0", "Unit Test Size List", new List<string>() } },
new object[] { false, new object[] { "UTSZ0", "Unit Test Size List", null } }
};
}
public static IEnumerable<string> GetTestDisplayNames() => new List<string> {
"All Valid", "Duplicate ID", "Missing ID", "Missing Name", "Empty List", "Null List"
};
我在測試資源管理器結果中收到了這條消息:
消息:值不能是 null。
參數名稱:方法 GetTestDisplayNames
我搜索了 web 關於如何使用DynamicDataDisplayName
但我無法提供一些東西; 我發現的只是如何使用DynamicData
問題在於GetTestDisplayNames
方法。 你應該像這樣定義它
public static string GetTestDisplayNames(MethodInfo methodInfo, object[] values)
{
var expected = (bool)values[0];
var inputs = (object[])values[1];
return $"{methodInfo.Name}({expected}, {inputs.Length})";
}
(這是一種可能的實現,但您當然可以返回不同的名稱)
此外,參數DynamicDataDisplayNameDeclaringType
應該指向類型,其中定義了GetTestDisplayNames
方法。 我相信,當您在相同的 class 中定義此方法作為測試方法( Should_BeReady
)時,可以跳過此參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.