







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: 2.6.1014.1 (2.6.0.0)
Syntax
C# |
---|
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#
The following examples shows how to setup the factory
to create loose mocks and later verify only verifiable expectations:
CopyC#
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); var foo = factory.Create<IFoo>(); var bar = factory.Create<IBar>(); // no need to call Verifiable() on the expectation // as we'll be validating all expectations anyway. foo.Expect(f => f.Do()); bar.Expect(b => b.Redo()); // exercise the mocks here factory.VerifyAll(); // At this point all expectations 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 expectation will also throw a MockException.

var factory = new MockFactory(MockBehavior.Loose); var foo = factory.Create<IFoo>(); var bar = factory.Create<IBar>(); // this expectation will be verified at the end of the "using" block foo.Expect(f => f.Do()).Verifiable(); // this expectation will NOT be verified foo.Expect(f => f.Calculate()); // this expectation will be verified at the end of the "using" block bar.Expect(b => b.Redo()).Verifiable(); // exercise the mocks here // note that because the mocks are Loose, members // called in the interfaces for which no matching // expectations exist will NOT throw exceptions, // and will rather return default values. factory.Verify(); // At this point verifiable expectations are already checked // and an optional MockException might be thrown.

var factory = new MockFactory(MockBehavior.Strict); // this particular one we want loose var foo = factory.Create<IFoo>(MockBehavior.Loose); var bar = factory.Create<IBar>(); // set expectations // exercise the mocks here factory.Verify();
Inheritance Hierarchy
Object
Moq..::.MockFactory
Moq..::.MockFactory