[英]xunit test previousValue
我想評估一個數據系列和 output 各自的先前值。 為此,我使用以下代碼:
private int PrevInt(int CurrentInt)
{
PrevIntList.Add(CurrentInt);
for (int i = 0; i < PrevIntList.Count; i++) { if (i >= 1) prevIntListValue = PrevIntList[i - 1]; }
return prevIntListValue;
}
要使用 Xunit 運行測試,我需要一個數據系列作為源(例如 1、2、3、4、5)和對我的方法的調用,該方法確定各自的前置值並確認它是正確的。 我怎樣才能正確地創建這樣的測試。
非常感謝支持!
請參閱我對你的for
循環的評論,你根本不需要它,你可以直接計算前一個元素的正確索引。
“安排、行動、斷言”范式將適用於這種情況,除了“行動”部分發生在安排期間。 您可以創建Theory
並提供數組中的整數序列。 在“排列”部分,您創建 class 的新實例並通過調用該方法設置列表,然后在操作部分根據預期值測試特定值。
假設 PrevIntList 是你 class 的成員,它可能看起來像這樣
public class YourClass
{
private List<int> PrevIntList = new List<int>();
public int PrevInt(int CurrentInt)
{
int prevIntListValue = -1;
PrevIntList.Add(CurrentInt);
for (int i = 0; i < PrevIntList.Count; i++) { if (i >= 1) prevIntListValue = PrevIntList[i - 1]; }
return prevIntListValue;
}
}
public class YourClassUnitTests
{
[Theory]
[InlineData(new int[] { 1, 2, 3, 4, 5 })]
public void PrevIntReturnsCorrectValue(int[] data)
{
// Sanity check-- the method only works when data has at least two elements
Assert.True(data.Length >= 2, $"Bad test data, array must have at least 2 elements but only has {data.Length}.");
// Arrange (and Act)
YourClass instance = new YourClass();
int actual = -1;
for (int i = 0; i < data.Length; i++)
{
actual = instance.PrevInt(data[i]);
}
// Act
// During arranging the method under test was called and the result saved in 'actual'
// Assert
int expected = data[data.Length - 2];
Assert.Equal(expected, actual);
}
}
當您提交家庭作業時,不要忘記感謝 Stack Overflow 的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.