Telerik® JustMock™ by Progress

Mocking properties is similar to mocking methods, but there are a few cases that need special attention like mocking indexers and particular set operations.

Consider the following interface for the examples in this article:

Mock Property Get Calls

The property get can be mocked like any other method call. We can arrange a return statement for a specific call (using Return), throw an exception (using Throw), raise an event when invoked (using Raise), etc.

Let's consider the following example:

Here we test that a call to foo.Value property returns the value we arranged.

Follows an example, showing mocking property in F#:

F# Copy imageCopy
member this.ShouldMockGetMemberThroughExpression() =

	let monkey = Mock.Create<IMonkey>()

	Mock.Arrange(monkey, fun ignore -> monkey.Name).Returns("Spike");  

	Assert.AreEqual(monkey.Name, "Spike")

In the arrange section we specify that a call to monkey.Name should return "Spike".

Mock Property Set Calls

The set operation can be mocked for both indexers and normal properties. Set operations are mocked using a special set entry point which is:Mock.ArrangeSet(lambda).

Property set mocking is useful when you want to make sure or to verify that a particular property is set with an expected value. For this reason we use a strict mocking.

With the matcher we set a requirement that the foo.Value property should have values larger than 3. When we set the value to a number less than 3, a MockException is thrown.

For asserting a property set in case of loose mocking, the following syntax is available:


Accordingly, we can do:

Here we make sure foo.Value was actually set to 1.

Refer to Do Instead for an example that shows how to use DoInstead on property set.

Mock Indexers

Indexers are special kind of properties that enable objects to be indexed in a similar manner to arrays.

Consider an interface with an indexer property.

Let's arrange that different values should be returned for different indexes.

  1. Create a mock.

  2. Arrange that a call to index 0 should return ping, a call to index 1 should return pong.

  3. Execute the calls.

  4. Finally, do the assertion.

Assert Indexed Set

Make sure that a specific index is set to a particular value.

The code above throws an exception once the zero-indexed item of foo is set to a value different than the expected one - i.e. foo.

Assert Indexed Set with Matching Criteria

Make sure that a specific index is set to a value matching a particular critera.

The first two set calls satisfy the requirements. However, the third call - foo[0] = "bar" throws an exception, because we arranged that the zero-indexed item can be set only to "foo".

See Also

Other Resources