简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM