MockRepository Class

Moq

Collapse image Expand Image Copy image CopyHover image
Utility repository class to use to construct multiple mocks when consistent verification is desired for all of them.

Namespace: Moq
Assembly: Moq (in Moq.dll) Version: 4.0.10827.0 (4.0.0.0)

Syntax

C#
public class MockRepository : MockFactory

Remarks

If multiple mocks will be created during a test, passing the desired MockBehavior (if different than the Default or the one passed to the repository constructor) and later verifying each mock can become repetitive and tedious.

This repository class helps in that scenario by providing a simplified creation of multiple mocks with a default MockBehavior (unless overriden by calling Create<(Of <<'(T>)>>)(MockBehavior)) and posterior verification.

Examples

The following is a straightforward example on how to create and automatically verify strict mocks using a MockRepository:
CopyC#
var repository = new MockRepository(MockBehavior.Strict);

var foo = repository.Create<IFoo>();
var bar = repository.Create<IBar>();

// no need to call Verifiable() on the setup 
// as we'll be validating all of them anyway.
foo.Setup(f => f.Do());
bar.Setup(b => b.Redo());

// exercise the mocks here

repository.VerifyAll(); 
// At this point all setups are already checked 
// and an optional MockException might be thrown. 
// Note also that because the mocks are strict, any invocation 
// that doesn't have a matching setup will also throw a MockException.
The following examples shows how to setup the repository to create loose mocks and later verify only verifiable setups:
CopyC#
var repository = new MockRepository(MockBehavior.Loose);

var foo = repository.Create<IFoo>();
var bar = repository.Create<IBar>();

// this setup will be verified when we verify the repository
foo.Setup(f => f.Do()).Verifiable();

// this setup will NOT be verified 
foo.Setup(f => f.Calculate());

// this setup will be verified when we verify the repository
bar.Setup(b => b.Redo()).Verifiable();

// exercise the mocks here
// note that because the mocks are Loose, members 
// called in the interfaces for which no matching
// setups exist will NOT throw exceptions, 
// and will rather return default values.

repository.Verify();
// At this point verifiable setups are already checked 
// and an optional MockException might be thrown.
The following examples shows how to setup the repository with a default strict behavior, overriding that default for a specific mock:
CopyC#
var repository = new MockRepository(MockBehavior.Strict);

// this particular one we want loose
var foo = repository.Create<IFoo>(MockBehavior.Loose);
var bar = repository.Create<IBar>();

// specify setups

// exercise the mocks here

repository.Verify();

Inheritance Hierarchy

System..::..Object
  Moq..::..MockFactory
    Moq..::..MockRepository

See Also