5

This question clearly shows how you can mock an index property with MOQ: How to Moq Setting an Indexed property

However, what if you have two index?

For instance, let's say you have a _Worksheet object (from vsto)

        var mockWorksheet = new Mock<_Worksheet>();

You want to create a property called Cells, such that you can use it like so:

        var range = worksheet.Cells[1,1];

Note: The range can be another mock, which could be mocked with: var mockRange = new Mock();

Any suggestions?

Community
  • 1
  • 1
zumalifeguard
  • 8,648
  • 5
  • 43
  • 56

1 Answers1

3

You mock property indexers just like anything else. They're treated just like property accessors, so you'd use SetupGet:

var mockWorksheet = new Mock<Worksheet>();
var mockRange = new Mock<Range>();
var mockCell = new Mock<Range>();

// Setup the Cells property to return a range     
mockWorksheet.SetupGet(p => p.Cells).Returns(mockRange.Object);

// Setup the range to return an expected "cell"
mockRange.SetupGet(p => p[1, 2]).Returns(mockCell.Object);

var expectedCell = mockWorksheet.Object.Cells[1, 2];

// expectedCell == mockCell.Object
Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
  • well for me using `mockType.SetupGet(p => p[1]).Returns(mockReturnType.Object);` is throwing `Missing method exception`. instead, I am mocking get_Item method and it is working as expected. `mockType.Setup(p => p.get_Item[1]).Returns(mockReturnType.Object);` – Prokurors Dec 21 '15 at 09:01