8

Moq.MockRepository.Of() 和 Moq.MockRepository.OneOf() 的正确用法是什么?我已经尝试过这样的事情来试图弄清楚。

var mr = new MockRepository(MockBehavior.Strict);
var m = mr.Of<ISomeInterface>();
foreach (var obj in m)
    cnt++;

我发现 cnt 只是不断增加,没有尽头。是什么赋予了?有关这方面的文档不会出现。

4

1 回答 1

11

您可以使用Moq.MockRepository.Of()通过表达式创建模拟。这最好用一个例子来解释:

public interface ITest
{
    String Say();
    Int32 DoSomething(Int32 a, Int32 b);
}

class Program
{
    public static void Main()
    {
        var repo = new MockRepository(MockBehavior.Strict);
        var mock = repo.Of<ITest>()
                       .Where(s => s.Say() == "Hi!")
                       .Where(s => s.DoSomething(5, 4) == 20)
                       .Where(s => s.DoSomething(4, 5) == 9)
                       .Where(s => s.DoSomething(It.IsAny<Int32>(), 7) == 99)
                       .First();

        Console.WriteLine(mock.Say());                 // prints Hi!
        Console.WriteLine(mock.DoSomething(5, 4));     // prints 20
        Console.WriteLine(mock.DoSomething(4, 5));     // prints 9
        Console.WriteLine(mock.DoSomething(23423, 7)); // prints 99
        Console.WriteLine(mock.DoSomething(0, 0));     // Fail due to MockBehavior.Strict

        Console.ReadKey();
    }
}
于 2012-05-18T08:37:56.593 回答