Mock(T) Class

Moq

Collapse image Expand Image Copy image CopyHover image
Provides a mock implementation of T.

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

Syntax

C#
public class Mock<T> : Mock
where T : class

Type Parameters

T
Type to mock, which can be an interface or a class.

Remarks

Any interface type can be used for mocking, but for classes, only abstract and virtual members can be mocked.

The behavior of the mock with regards to the setups and the actual calls is determined by the optional MockBehavior that can be passed to the Mock<(Of <(<'T>)>)>(MockBehavior) constructor.

Examples

The following example shows establishing setups with specific values for method invocations:
CopyC#
// Arrange
var order = new Order(TALISKER, 50);
var mock = new Mock<IWarehouse>();

mock.Setup(x => x.HasInventory(TALISKER, 50)).Returns(true);

// Act
order.Fill(mock.Object);

// Assert
Assert.True(order.IsFilled);
The following example shows how to use the It class to specify conditions for arguments instead of specific values:
CopyC#
// Arrange
var order = new Order(TALISKER, 50);
var mock = new Mock<IWarehouse>();

// shows how to expect a value within a range
mock.Setup(x => x.HasInventory(
            It.IsAny<string>(),
            It.IsInRange(0, 100, Range.Inclusive)))
     .Returns(false);

// shows how to throw for unexpected calls.
mock.Setup(x => x.Remove(
            It.IsAny<string>(),
            It.IsAny<int>()))
     .Throws(new InvalidOperationException());

// Act
order.Fill(mock.Object);

// Assert
Assert.False(order.IsFilled);

Inheritance Hierarchy

System..::..Object
  Moq..::..Mock
    Moq..::..Mock<(Of <(<'T>)>)>

See Also