MAckerman
MAckerman

Reputation: 428

Moq - Object type casting and comparison

I'm trying to use an IHTMLSelectElement with Moq. My code is something like:

// create a select element
var selectElem = new Mock<IHTMLSelectElement>(MockBehavior.Strict);
// set the select element
selectElem.Setup(f => f.length).Returns(20);
selectElem.Setup(f => f.name).Returns("selectElem");            
// get the object
IHTMLSelectElement ihse = selectElem.Object;

Then in my production code method, I do:

var selectEle = (element as mshtml.IHTMLSelectElement);
if (selectEle != null)
{

My problem is that the type cast doesn't work because when using Moq the type is actually: Castle.Proxies.IHTMLSelectElementProxy_1

Casting this to IHTMLSelectElement returns a null object.

Any idea on how I can make this work?

Upvotes: 0

Views: 2849

Answers (1)

AD.Net
AD.Net

Reputation: 13399

You'll need to make it injectable, either a property or a input parameter to a method, depending on the code. And then you can inject the with the MOQ object. The two lines of your code should not be doing the "as", it should be dealing with the correct type of element directly.

Upvotes: 1

Related Questions