Ban*_*San 6 .net c# unit-testing moq mocking
我有一个类似于下面的设置:
[TestMethod]
public void NoIntegers()
{
Mock<IBar> mockBar = new Mock<IBar>(MockBehavior.Strict);
Mock<IEnumerable<int>> mockIntegers = new Mock<IEnumerable<int>>(MockBehavior.Strict);
mockBar
.SetupGet(x => x.Integers)
.Returns(mockIntegers.Object);
mockIntegers
.Setup(x => x.Any())
.Returns(false);
Assert.IsFalse(new Foo(mockBar.Object).AreThereIntegers());
}
public interface IBar
{
IEnumerable<int> Integers { get; }
}
public class Foo
{
private IBar _bar;
public Foo(IBar bar)
{
_bar = bar;
}
public bool AreThereIntegers()
{
return _bar.Integers.Any();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当它运行时,它无法初始化模拟
Test method NoIntegers threw exception: System.NotSupportedException: Expression references a method that does not belong to the mocked object: x => x.Any<Int32>()
Run Code Online (Sandbox Code Playgroud)
我尝试添加It.IsAny()几种形式:
mockIntegers
.Setup(x => x.Any(It.IsAny<IEnumerable<int>>(), It.IsAny<Func<int, bool>>()))
.Returns(false);
// No method with this signiture
mockIntegers
.Setup(x => x.Any(It.IsAny<Func<int, bool>>()))
.Returns(false);
// Throws: Test method NoIntegers threw exception:
// System.NotSupportedException:
// Expression references a method that does not belong to the mocked object:
// x => x.Any<Int32>(It.IsAny<Func`2>())
Run Code Online (Sandbox Code Playgroud)
我需要模拟什么才能运行它?
您只需要模拟Integers财产。不需要模拟(无论如何你都不能这样做,因为它是一个扩展方法),因为它是SUTAny()的一部分。针对两种情况,您应该如何执行此操作:
[TestMethod]
public void NoIntegers()
{
Mock<IBar> mockBar = new Mock<IBar>(MockBehavior.Strict);
mockBar.SetupGet(x => x.Integers)
.Returns(new List<int>());
Assert.IsFalse(new Foo(mockBar.Object).AreThereIntegers());
}
[TestMethod]
public void HasIntegers()
{
Mock<IBar> mockBar = new Mock<IBar>(MockBehavior.Strict);
mockBar.SetupGet(x => x.Integers)
.Returns(new List<int>{ 3, 5, 6});
Assert.IsTrue(new Foo(mockBar.Object).AreThereIntegers());
}
Run Code Online (Sandbox Code Playgroud)