MockFactory Class

Moq

Collapse image Expand Image Copy image CopyHover image
Utility factory 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#
[ObsoleteAttribute("This class has been renamed to MockRepository. MockFactory will be retired in v5.", 
	false)]
public class 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 factory constructor) and later verifying each mock can become repetitive and tedious.

This factory 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 MockFactory:
CopyC#
var factory = new MockFactory(MockBehavior.Strict);

var foo = factory.Create<IFoo>();
var bar = factory.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

factory.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 factory to create loose mocks and later verify only verifiable setups:
CopyC#
var factory = new MockFactory(MockBehavior.Loose);

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

// this setup will be verified when we verify the factory
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 factory
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.

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

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

// specify setups

// exercise the mocks here

factory.Verify();

Inheritance Hierarchy

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

See Also