As(TInterface) Method

Moq

Collapse image Expand Image Copy image CopyHover image
Adds an interface implementation to the mock, allowing setups to be specified for it.

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

Syntax

C#
public virtual Mock<TInterface> As<TInterface>()
where TInterface : class

Type Parameters

TInterface
Type of interface to cast the mock to.

Remarks

This method can only be called before the first use of the mock Object property, at which point the runtime type has already been generated and no more interfaces can be added to it.

Also, TInterface must be an interface and not a class, which must be specified when creating the mock instead.

Examples

The following example creates a mock for the main interface and later adds IDisposable to it to verify it's called by the consumer code:
CopyC#
var mock = new Mock<IProcessor>();
mock.Setup(x => x.Execute("ping"));

// add IDisposable interface
var disposable = mock.As<IDisposable>();
disposable.Setup(d => d.Dispose()).Verifiable();

Exceptions

Exception Condition
System..::..InvalidOperationException The mock type has already been generated by accessing the Object property.
System..::..ArgumentException The TInterface specified is not an interface.

See Also