Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Moq to Mock an index property with that has two indexes

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?

like image 688
zumalifeguard Avatar asked Oct 20 '22 23:10

zumalifeguard


1 Answers

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
like image 73
Patrick Quirk Avatar answered Oct 23 '22 03:10

Patrick Quirk