IMock(T) Interface

Moq 2.6

Provides a mock implementation of T.

Namespace:  Moq
Assembly:  Moq (in Moq.dll) Version: 2.6.1014.1 (2.6.0.0)

Syntax

C#
public interface IMock<T>
where T : class

Type Parameters

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

Remarks

Only abstract and virtual members of classes can be mocked.

The behavior of the mock with regards to the expectations 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 setting expectations with specific values for method invocations:
CopyC#
//setup - data
var order = new Order(TALISKER, 50);
var mock = new Mock<IWarehouse>();

//setup - expectations
mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true);

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

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

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

//shows how to throw for unexpected calls. contrast with the "verify" approach of other mock libraries.
mock.Expect(x => x.Remove(
        It.IsAny<string>(), 
        It.IsAny<int>()))
    .Throws(new InvalidOperationException());

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

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

See Also