Get(T) Method

Moq

Collapse image Expand Image Copy image CopyHover image
Retrieves the mock object for the given object instance.

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

Syntax

C#
public static Mock<T> Get<T>(
	T mocked
)
where T : class

Parameters

mocked
Type: T
The instance of the mocked object.

Type Parameters

T
Type of the mock to retrieve. Can be omitted as it's inferred from the object instance passed in as the mocked instance.

Return Value

The mock associated with the mocked object.

Examples

The following example shows how to add a new setup to an object instance which is not the original Mock<(Of <(<'T>)>)> but rather the object associated with it:
CopyC#
// Typed instance, not the mock, is retrieved from some test API.
HttpContextBase context = GetMockContext();

// context.Request is the typed object from the "real" API
// so in order to add a setup to it, we need to get
// the mock that "owns" it
Mock<HttpRequestBase> request = Mock.Get(context.Request);
mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
     .Returns(tempUrl);

Exceptions

Exception Condition
System..::..ArgumentException The received mocked instance was not created by Moq.

See Also