Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Moq.MockRepository.Of() method

What is the proper use of Moq.MockRepository.Of() and Moq.MockRepository.OneOf()? I've tried something like this to try to figure it out.

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

I've found that cnt just keeps incrementing to no end. What gives? Documentation regarding this is not forthcoming.

like image 490
Shawn de Wet Avatar asked May 17 '12 15:05

Shawn de Wet


1 Answers

You can use Moq.MockRepository.Of() to create mocks via expressions. This is best explained by an example:

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();
    }
}
like image 133
sloth Avatar answered Oct 05 '22 11:10

sloth