How to Mock a readonly property whose value depends on another property of the Mock

(As indicated by the tags, I am using moq).

I have an interface like this:

interface ISource
{
  string Name { get; set; }
  int Id { get; set; }
}

interface IExample
{
  string Name { get; }
  ISource Source { get; set; }
}

In my application, concrete instances of IExample accept a DTO (IDataTransferObject) as the Source. Some properties on the concrete implementation of IExample are simply delegated to the Source. Like this...

class Example : IExample
{
  IDataTransferObject Source { get; set; }

  string Name { get { return _data.Name; } }
}

I would like to create a standalone mock of IExample (standalone meaning that I cannot use a captured variable because several instances of the IExample mock will be created in the course of a test) and setup the Mock such that IExample.Name returns the value of IExample.Source.Name. So, I would like to create a mock something like this:

var example = new Mock<IExample>();
example.SetupProperty(ex => ex.Source);
example.SetupGet(ex => ex.Name).Returns(what can I put here to return ex.Source.Name);

Essentially, I want to configure the mock to return, as the value of one property, the value of a property of a subobject of the mock.

Thanks.

Answers


You could probably use:

example.SetupGet(ex => ex.Name).Returns(() => example.Object.Source.Name);

The value to be returned will then be determined when the property is accessed, and will be taken from Name property of the mock's Source property.


Need Your Help

Bind to Count of items in the DataContext

wpf binding

I want to bind to the Count/amount of items within my DataContext.