我正在使用xUnit和MOQ,我正在尝试测试这个:
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach (var item in list)
action(item);
}
}
我试过这个,但没有交易:
[Fact]
public void ForEach()
{
var list = new List<string>() { "string1", "string2" };
list.ForEach(x =>
{
x += "-passed";
});
foreach (var item in list)
item.Should().EndWith("-passed");
}
你将如何测试?
答案 0 :(得分:1)
在您当前的测试中,您只是在操作中修改本地x
变量。我会创建一个新列表:
var list = new List<string>() { "string1", "string2" };
var dest = new List<string>();
list.ForEach(s => { dest.Add(x + "-passed"); });
foreach (var item in dest)
{
item.Should().EndWith("-passed");
}
您可能还想保持调用频率的计数:
int called = 0;
list.ForEach(s => {
dest.Add(x + "-passed");
called++;
});
Assert.AreEqual(called, list.Count);
答案 1 :(得分:1)
List<int> items = new List<int>();
Action<int> act = i => { items.Add(i); };
Enumerable.Range(0, 10).ForEach(act).ToList();
Assert.That(items.Count, Is.EqualTo(10));
...