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 を使用することですが、テスト結果が異なります (2 番目のケースでは、CustomMethods がモックで呼び出されます)。
誰かがその行動を説明できますか?