gpt4 book ai didi

c# - SelectMany 时最小起订量验证失败

转载 作者:太空狗 更新时间:2023-10-30 00:32:07 27 4
gpt4 key购买 nike

我正在使用 NUnit、Moq 和 StructureMap。

我有以下 NUnit 测试:

    [Test]
public void ShouldCallCustomMethod_ForAllICustomInterfaceMocks()
{
var customInterfaceMock1 = new Mock<ICustomInterface>();
var customInterfaceMock2 = new Mock<ICustomInterface>();

ObjectFactory.Inject(customInterfaceMock1.Object);
ObjectFactory.Inject(customInterfaceMock2.Object);

var sut = new SUT();
sut.MethodThatShouldCallCustomMethodOnMocks();

customInterfaceMock1.Verify(m => m.CustomMethod());
customInterfaceMock2.Verify(m => m.CustomMethod());
}

ICustomInterface:

public interface ICustomInterface
{
IEnumerable<Type> CustomMethod();
}

现在如果 SUT 类的实现如下所示:

public class SUT
{
public IEnumerable<Type> MethodThatShouldCallCustomMethodOnMocks()
{
var result = ObjectFactory.GetAllInstances<ICustomInterface>()
.SelectMany(i => i.CustomMethod());


return result;
}
}

由于未在模拟上调用方法 CustomMethod,上述测试失败。但是,如果我将 SUT 类的实现更改为:

public class SUT
{
public IEnumerable<Type> MethodThatShouldCallCustomMethodOnMocks()
{
var customInterfaceInstances = ObjectFactory.GetAllInstances<ICustomInterface>();

foreach (var instance in customInterfaceInstances)
instance.CustomMethod();


return ...
}
}

测试通过!不同之处在于,我没有使用 SelectMany 进行迭代,而是使用 foreach,但测试结果不同(在第二种情况下,CustomMethods 确实在模拟上被调用)。

有人可以解释这种行为吗?

最佳答案

我认为这可能是延迟执行的情况。 SelectMany 不会立即执行。必须枚举返回的 IEnumerable 才能调用您的方法。尝试在 SelectMany() 方法之后添加 ToList() 以强制计算从 SelectMany 返回的 IEnumerable

关于c# - SelectMany 时最小起订量验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19954631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com